diff --git a/.checkstyle b/.checkstyle deleted file mode 100644 index 15ff199..0000000 --- a/.checkstyle +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..bc7e88a --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# style: format with google java style guide (#68) +a927b29336b013b91d3aaa5efa7c94dcc80fd7fa \ No newline at end of file diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index d856de8..0000000 --- a/checkstyle.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml index 81039aa..baa0a6b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -7,6 +8,11 @@ IES User Repository Core IES User repository domain und use-case implementations + + Sitepark + https://www.sitepark.com + + The MIT License @@ -14,11 +20,6 @@ - - Sitepark - https://www.sitepark.com - - veltrup@sitepark @@ -34,6 +35,13 @@ + + scm:git:git@github.com:sitepark/ies-userrepository-core.git + scm:git:git@github.com:sitepark/ies-userrepository-core.git + HEAD + https://github.com/sitepark/ies-userrepository-core + + 5.10.1 4.8.3 @@ -42,13 +50,6 @@ true - - scm:git:git@github.com:sitepark/ies-userrepository-core.git - scm:git:git@github.com:sitepark/ies-userrepository-core.git - https://github.com/sitepark/ies-userrepository-core - HEAD - - @@ -72,27 +73,27 @@ org.apache.logging.log4j log4j-api - 2.22.1 + 2.23.1 com.fasterxml.jackson.datatype jackson-datatype-jdk8 - 2.16.1 + 2.17.0 com.fasterxml.jackson.datatype jackson-datatype-jsr310 - 2.16.1 + 2.17.0 com.fasterxml.jackson.core jackson-databind - 2.16.1 + 2.17.0 + + + google-java-format + + + + + 1.19.2 + + true + false + + + + + + + pom.xml + + + + -1 + + - checkstyle - verify + + spotless-check check + verify - com.github.spotbugs spotbugs-maven-plugin - 4.8.3.0 - - - verify - - check - - - + 4.8.3.1 Max Low @@ -371,20 +384,19 @@ ${spotbugs.version} - - - org.apache.maven.plugins - maven-pmd-plugin - 3.21.2 - pmd - verify check + verify + + + org.apache.maven.plugins + maven-pmd-plugin + 3.21.2 pmd-ruleset.xml @@ -393,8 +405,18 @@ true 5 true - false + false + + + + pmd + + check + + verify + + diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/AccessToken.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/AccessToken.java index 25a2ebe..cb4d0c5 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/AccessToken.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/AccessToken.java @@ -1,5 +1,9 @@ package com.sitepark.ies.userrepository.core.domain.entity; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collections; @@ -7,318 +11,287 @@ import java.util.Objects; import java.util.Optional; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - -/** - * An access token enables authentication as a user - * without specifying a username and password. - */ +/** An access token enables authentication as a user without specifying a username and password. */ @JsonDeserialize(builder = AccessToken.Builder.class) public final class AccessToken { - private final String id; + private final String id; + + private final String user; + + private final String name; + + private final String token; + + private final OffsetDateTime createdAt; + + private final OffsetDateTime expiresAt; + + private final OffsetDateTime lastUsed; + + private final List scopeList; + + private final boolean impersonation; + + private final boolean active; + + private final boolean revoked; + + protected AccessToken(Builder builder) { + this.id = builder.id; + this.user = builder.user; + this.name = builder.name; + this.token = builder.token; + this.createdAt = builder.createdAt; + this.expiresAt = builder.expiresAt; + this.lastUsed = builder.lastUsed; + this.scopeList = Collections.unmodifiableList(builder.scopeList); + this.impersonation = builder.impersonation; + this.active = builder.active; + this.revoked = builder.revoked; + } + + public Optional getId() { + if (this.id == null) { + return Optional.empty(); + } + return Optional.of(this.id); + } + + public String getUser() { + return this.user; + } + + public String getName() { + return this.name; + } - private final String user; + public Optional getToken() { + return Optional.ofNullable(this.token); + } - private final String name; + public Optional getCreatedAt() { + return Optional.ofNullable(this.createdAt); + } - private final String token; - - private final OffsetDateTime createdAt; + public Optional getExpiresAt() { + return Optional.ofNullable(this.expiresAt); + } - private final OffsetDateTime expiresAt; - - private final OffsetDateTime lastUsed; - - private final List scopeList; - - private final boolean impersonation; - - private final boolean active; - - private final boolean revoked; + public Optional getLastUsed() { + return Optional.ofNullable(this.lastUsed); + } - protected AccessToken(Builder builder) { - this.id = builder.id; - this.user = builder.user; - this.name = builder.name; - this.token = builder.token; - this.createdAt = builder.createdAt; - this.expiresAt = builder.expiresAt; - this.lastUsed = builder.lastUsed; - this.scopeList = Collections.unmodifiableList(builder.scopeList); - this.impersonation = builder.impersonation; - this.active = builder.active; - this.revoked = builder.revoked; - } - - public Optional getId() { - if (this.id == null) { - return Optional.empty(); - } else { - return Optional.of(this.id); - } - } - - public String getUser() { - return this.user; - } - - public String getName() { - return this.name; - } - - public Optional getToken() { - return Optional.ofNullable(this.token); - } - - public Optional getCreatedAt() { - return Optional.ofNullable(this.createdAt); - } - - public Optional getExpiresAt() { - return Optional.ofNullable(this.expiresAt); - } - - public Optional getLastUsed() { - return Optional.ofNullable(this.lastUsed); - } - - @SuppressFBWarnings("EI_EXPOSE_REP") - public List getScopeList() { - return this.scopeList; - } + @SuppressFBWarnings("EI_EXPOSE_REP") + public List getScopeList() { + return this.scopeList; + } - public boolean isImpersonation() { - return this.impersonation; - } + public boolean isImpersonation() { + return this.impersonation; + } - public boolean isActive() { - return this.active; - } + public boolean isActive() { + return this.active; + } - public boolean isRevoked() { - return this.revoked; - } - - public static Builder builder() { - return new Builder(); - } - - public Builder toBuilder() { - return new Builder(this); - } - - @Override - public final int hashCode() { - return Objects.hash( - this.id, - this.user, - this.name, - this.token, - this.createdAt, - this.expiresAt, - this.lastUsed, - this.scopeList, - this.impersonation, - this.active, - this.revoked); - } - - @Override - @SuppressWarnings({ - "PMD.CyclomaticComplexity", - "PMD.NPathComplexity" - }) - public final boolean equals(Object o) { - - if (!(o instanceof AccessToken)) { - return false; - } - - AccessToken accessToken = (AccessToken)o; - - if (!Objects.equals(this.id, accessToken.id)) { - return false; - } else if (!Objects.equals(this.user, accessToken.user)) { - return false; - } else if (!Objects.equals(this.name, accessToken.name)) { - return false; - } else if (!Objects.equals(this.token, accessToken.token)) { - return false; - } else if (!Objects.equals(this.createdAt, accessToken.createdAt)) { - return false; - } else if (!Objects.equals(this.expiresAt, accessToken.expiresAt)) { - return false; - } else if (!Objects.equals(this.lastUsed, accessToken.lastUsed)) { - return false; - } else if (!Objects.equals(this.scopeList, accessToken.scopeList)) { - return false; - } else if (!Objects.equals(this.impersonation, accessToken.impersonation)) { - return false; - } else if (!Objects.equals(this.active, accessToken.active)) { - return false; - } else if (!Objects.equals(this.revoked, accessToken.revoked)) { - return false; - } - - return true; - } - - @SuppressWarnings("PMD.TooManyMethods") - @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") - public static final class Builder { - - private String id; - - private String user; - - private String name; - - private String token; - - private OffsetDateTime createdAt; - - private OffsetDateTime expiresAt; - - private OffsetDateTime lastUsed; - - private final List scopeList = new ArrayList<>(); - - private boolean impersonation; - - private boolean active = true; - - private boolean revoked; - - protected Builder() { - } - - protected Builder(AccessToken accessToken) { - this.id = accessToken.id; - this.user = accessToken.user; - this.name = accessToken.name; - this.token = accessToken.token; - this.createdAt = accessToken.createdAt; - this.expiresAt = accessToken.expiresAt; - this.lastUsed = accessToken.lastUsed; - this.scopeList.addAll(accessToken.scopeList); - this.impersonation = accessToken.impersonation; - this.active = accessToken.active; - this.revoked = accessToken.revoked; - } - - public Builder id(String id) { - Objects.requireNonNull(id, "id is null"); - if (!Identifier.isId(id)) { - throw new IllegalArgumentException(id + " is not an id"); - } - this.id = id; - return this; - } - - public Builder user(String user) { - Objects.requireNonNull(user, "user is null"); - if (!Identifier.isId(user)) { - throw new IllegalArgumentException(user + " is not an user id"); - } - this.user = user; - return this; - } - - public Builder name(String name) { - Objects.requireNonNull(name, "name is null"); - this.requireNonBlank(name, "name is blank"); - this.name = name; - return this; - } - - public Builder token(String token) { - Objects.requireNonNull(token, "token is null"); - this.requireNonBlank(token, "token is blank"); - this.token = token; - return this; - } - - public Builder createdAt(OffsetDateTime createdAt) { - Objects.requireNonNull(createdAt, "createdAt is null"); - this.createdAt = createdAt; - return this; - } - - public Builder expiresAt(OffsetDateTime expiresAt) { - Objects.requireNonNull(expiresAt, "expiresAt is null"); - this.expiresAt = expiresAt; - return this; - } - - public Builder lastUsed(OffsetDateTime lastUsed) { - Objects.requireNonNull(lastUsed, "lastUsed is null"); - this.lastUsed = lastUsed; - return this; - } - - @JsonSetter - public Builder scopeList(List scopeList) { - Objects.requireNonNull(scopeList, "scopeList is null"); - this.scopeList.clear(); - for (String scope : scopeList) { - this.scope(scope); - } - return this; - } - - public Builder scopeList(String... scopeList) { - Objects.requireNonNull(scopeList, "scopeList is null"); - this.scopeList.clear(); - for (String scope : scopeList) { - this.scope(scope); - } - return this; - } - - public Builder scope(String scope) { - Objects.requireNonNull(scope, "scope is null"); - this.requireNonBlank(scope, "scope is blank"); - this.scopeList.add(scope); - return this; - } - - public Builder impersonation(boolean impersonation) { - this.impersonation = impersonation; - return this; - } - - public Builder active(boolean active) { - this.active = active; - return this; - } - - public Builder revoked(boolean revoked) { - this.revoked = revoked; - return this; - } - - public AccessToken build() { - - if (this.user == null) { - throw new IllegalStateException("user is not set"); - } - if (this.name == null) { - throw new IllegalStateException("name is not set"); - } - - return new AccessToken(this); - } - - private void requireNonBlank(String s, String message) { - if (s.isBlank()) { - throw new IllegalArgumentException(message); - } - } - } + public boolean isRevoked() { + return this.revoked; + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + @Override + public int hashCode() { + return Objects.hash( + this.id, + this.user, + this.name, + this.token, + this.createdAt, + this.expiresAt, + this.lastUsed, + this.scopeList, + this.impersonation, + this.active, + this.revoked); + } + + @Override + public boolean equals(Object o) { + + if (!(o instanceof AccessToken that)) { + return false; + } + + return Objects.equals(this.id, that.id) + && Objects.equals(this.user, that.user) + && Objects.equals(this.name, that.name) + && Objects.equals(this.token, that.token) + && Objects.equals(this.createdAt, that.createdAt) + && Objects.equals(this.expiresAt, that.expiresAt) + && Objects.equals(this.lastUsed, that.lastUsed) + && Objects.equals(this.scopeList, that.scopeList) + && Objects.equals(this.impersonation, that.impersonation) + && Objects.equals(this.active, that.active) + && Objects.equals(this.revoked, that.revoked); + } + + @SuppressWarnings("PMD.TooManyMethods") + @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") + public static final class Builder { + + private String id; + + private String user; + + private String name; + + private String token; + + private OffsetDateTime createdAt; + + private OffsetDateTime expiresAt; + + private OffsetDateTime lastUsed; + + private final List scopeList = new ArrayList<>(); + + private boolean impersonation; + + private boolean active = true; + + private boolean revoked; + + protected Builder() {} + + protected Builder(AccessToken accessToken) { + this.id = accessToken.id; + this.user = accessToken.user; + this.name = accessToken.name; + this.token = accessToken.token; + this.createdAt = accessToken.createdAt; + this.expiresAt = accessToken.expiresAt; + this.lastUsed = accessToken.lastUsed; + this.scopeList.addAll(accessToken.scopeList); + this.impersonation = accessToken.impersonation; + this.active = accessToken.active; + this.revoked = accessToken.revoked; + } + + public Builder id(String id) { + Objects.requireNonNull(id, "id is null"); + if (!Identifier.isId(id)) { + throw new IllegalArgumentException(id + " is not an id"); + } + this.id = id; + return this; + } + + public Builder user(String user) { + Objects.requireNonNull(user, "user is null"); + if (!Identifier.isId(user)) { + throw new IllegalArgumentException(user + " is not an user id"); + } + this.user = user; + return this; + } + + public Builder name(String name) { + Objects.requireNonNull(name, "name is null"); + this.requireNonBlank(name, "name is blank"); + this.name = name; + return this; + } + + public Builder token(String token) { + Objects.requireNonNull(token, "token is null"); + this.requireNonBlank(token, "token is blank"); + this.token = token; + return this; + } + + public Builder createdAt(OffsetDateTime createdAt) { + Objects.requireNonNull(createdAt, "createdAt is null"); + this.createdAt = createdAt; + return this; + } + + public Builder expiresAt(OffsetDateTime expiresAt) { + Objects.requireNonNull(expiresAt, "expiresAt is null"); + this.expiresAt = expiresAt; + return this; + } + + public Builder lastUsed(OffsetDateTime lastUsed) { + Objects.requireNonNull(lastUsed, "lastUsed is null"); + this.lastUsed = lastUsed; + return this; + } + + @JsonSetter + public Builder scopeList(List scopeList) { + Objects.requireNonNull(scopeList, "scopeList is null"); + this.scopeList.clear(); + for (String scope : scopeList) { + this.scope(scope); + } + return this; + } + + public Builder scopeList(String... scopeList) { + Objects.requireNonNull(scopeList, "scopeList is null"); + this.scopeList.clear(); + for (String scope : scopeList) { + this.scope(scope); + } + return this; + } + + public Builder scope(String scope) { + Objects.requireNonNull(scope, "scope is null"); + this.requireNonBlank(scope, "scope is blank"); + this.scopeList.add(scope); + return this; + } + + public Builder impersonation(boolean impersonation) { + this.impersonation = impersonation; + return this; + } + + public Builder active(boolean active) { + this.active = active; + return this; + } + + public Builder revoked(boolean revoked) { + this.revoked = revoked; + return this; + } + + public AccessToken build() { + + if (this.user == null) { + throw new IllegalStateException("user is not set"); + } + if (this.name == null) { + throw new IllegalStateException("name is not set"); + } + + return new AccessToken(this); + } + + private void requireNonBlank(String s, String message) { + if (s.isBlank()) { + throw new IllegalArgumentException(message); + } + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Anchor.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Anchor.java index 658164d..8986a2a 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Anchor.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Anchor.java @@ -1,12 +1,11 @@ package com.sitepark.ies.userrepository.core.domain.entity; +import com.fasterxml.jackson.annotation.JsonValue; +import com.sitepark.ies.userrepository.core.domain.exception.InvalidAnchorException; import java.io.Serializable; import java.util.Objects; import java.util.regex.Pattern; -import com.fasterxml.jackson.annotation.JsonValue; -import com.sitepark.ies.userrepository.core.domain.exception.InvalidAnchorException; - /** *

An "anchor" in the IES system is an additional optional field that * serves as an alternative identifier. @@ -36,77 +35,74 @@ */ public final class Anchor implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String VALID_CHARS_REGEX = "[a-zA-Z0-9_.\\-]+"; + private static final long serialVersionUID = 1L; - private static final Pattern VALIDATOR_PATTERN = Pattern.compile(VALID_CHARS_REGEX); + public static final String VALID_CHARS_REGEX = "[a-zA-Z0-9_.\\-]+"; - private static final Pattern ONLY_NUMBERS_PATTERN = Pattern.compile("[0-9]+"); + private static final Pattern VALIDATOR_PATTERN = Pattern.compile(VALID_CHARS_REGEX); - /** - * Used to reset anchor when saving entries. - */ - public static final Anchor EMPTY = new Anchor(""); + private static final Pattern ONLY_NUMBERS_PATTERN = Pattern.compile("[0-9]+"); - @JsonValue - private final String name; + /** + * Used to reset anchor when saving entries. + */ + public static final Anchor EMPTY = new Anchor(""); - private Anchor(String name) { - this.name = name; - } + @JsonValue private final String name; - public static Anchor ofString(String name) { + private Anchor(String name) { + this.name = name; + } - if (name == null) { - return null; - } + public static Anchor ofString(String name) { - if (name.isBlank()) { - return EMPTY; - } + if (name == null) { + return null; + } - Anchor.validate(name); - return new Anchor(name); - } + if (name.isBlank()) { + return EMPTY; + } - public String getName() { - return this.name; - } + Anchor.validate(name); + return new Anchor(name); + } - /** - * @throws InvalidAnchorException - */ - private static void validate(String name) { + public String getName() { + return this.name; + } - if (ONLY_NUMBERS_PATTERN.matcher(name).matches()) { - throw new InvalidAnchorException(name, "Anchor must not only consist of numbers"); - } + /** + * @throws InvalidAnchorException + */ + private static void validate(String name) { - if (!VALIDATOR_PATTERN.matcher(name).matches()) { - throw new InvalidAnchorException(name, "Anchor contains Spaces"); - } - } + if (ONLY_NUMBERS_PATTERN.matcher(name).matches()) { + throw new InvalidAnchorException(name, "Anchor must not only consist of numbers"); + } - @Override - public int hashCode() { - return this.name != null ? this.name.hashCode() : 0; - } + if (!VALIDATOR_PATTERN.matcher(name).matches()) { + throw new InvalidAnchorException(name, "Anchor contains Spaces"); + } + } + @Override + public int hashCode() { + return this.name != null ? this.name.hashCode() : 0; + } - @Override - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { - if (!(o instanceof Anchor)) { - return false; - } + if (!(o instanceof Anchor anchor)) { + return false; + } - Anchor anchor = (Anchor)o; - return Objects.equals(this.name, anchor.name); - } + return Objects.equals(this.name, anchor.name); + } - @Override - public String toString() { - return this == EMPTY ? "EMPTY" : this.name; - } + @Override + public String toString() { + return this == EMPTY ? "EMPTY" : this.name; + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/GenderType.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/GenderType.java index 5ba56e9..a86ac80 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/GenderType.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/GenderType.java @@ -6,8 +6,8 @@ * for diverse gender expressions. */ public enum GenderType { - UNKNOWN, - FEMALE, - MALE, - DIVERSE + UNKNOWN, + FEMALE, + MALE, + DIVERSE } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identifier.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identifier.java index b10a59f..b2dc1e1 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identifier.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identifier.java @@ -1,106 +1,101 @@ package com.sitepark.ies.userrepository.core.domain.entity; +import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Objects; import java.util.Optional; -import com.fasterxml.jackson.annotation.JsonCreator; - public final class Identifier { - private static final int MAX_ID_LENGTH = 19; - - private static final String ZERO_ID = "0"; - - private final String id; - - private final Anchor anchor; - - private Identifier(String id) { - this.id = id; - this.anchor = null; - } - - private Identifier(Anchor anchor) { - this.id = null; - this.anchor = anchor; - } - - public static Identifier ofId(String id) { - if (!isId(id)) { - throw new IllegalArgumentException("invalid id: " + id); - } - return new Identifier(id); - } - - public static Identifier ofAnchor(Anchor anchor) { - Objects.requireNonNull(anchor, "anchor is null"); - return new Identifier(anchor); - } - - @JsonCreator - public static Identifier ofString(String identifier) { - Objects.requireNonNull(identifier, "identifier is null"); - if (identifier.isBlank()) { - throw new IllegalArgumentException("identifier is blank"); - } - if (isId(identifier)) { - return new Identifier(identifier); - } - return new Identifier(Anchor.ofString(identifier)); - } - - public Optional getId() { - return Optional.ofNullable(this.id); - } - - public Optional getAnchor() { - return Optional.ofNullable(this.anchor); - } - - public static boolean isId(String str) { - - if (ZERO_ID.equals(str)) { - throw new IllegalArgumentException("id should be greater than 0"); - } - - int length = str.length(); - if (length > MAX_ID_LENGTH) { - return false; - } - - for (int i = 0; i < length; i++) { - char c = str.charAt(i); - if (c < '0' || c > '9') { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - return Objects.hash(this.id, this.anchor); - } - - - @Override - public boolean equals(Object o) { - - if (!(o instanceof Identifier)) { - return false; - } - - Identifier that = (Identifier)o; - return - Objects.equals(this.id, that.id) && - Objects.equals(this.anchor, that.anchor); - } - - @Override - public String toString() { - if (this.id != null) { - return this.id; - } - return this.anchor.toString(); - } + private static final int MAX_ID_LENGTH = 19; + + private static final String ZERO_ID = "0"; + + private final String id; + + private final Anchor anchor; + + private Identifier(String id) { + this.id = id; + this.anchor = null; + } + + private Identifier(Anchor anchor) { + this.id = null; + this.anchor = anchor; + } + + public static Identifier ofId(String id) { + if (!isId(id)) { + throw new IllegalArgumentException("invalid id: " + id); + } + return new Identifier(id); + } + + public static Identifier ofAnchor(Anchor anchor) { + Objects.requireNonNull(anchor, "anchor is null"); + return new Identifier(anchor); + } + + @JsonCreator + public static Identifier ofString(String identifier) { + Objects.requireNonNull(identifier, "identifier is null"); + if (identifier.isBlank()) { + throw new IllegalArgumentException("identifier is blank"); + } + if (isId(identifier)) { + return new Identifier(identifier); + } + return new Identifier(Anchor.ofString(identifier)); + } + + public Optional getId() { + return Optional.ofNullable(this.id); + } + + public Optional getAnchor() { + return Optional.ofNullable(this.anchor); + } + + public static boolean isId(String str) { + + if (ZERO_ID.equals(str)) { + throw new IllegalArgumentException("id should be greater than 0"); + } + + int length = str.length(); + if (length > MAX_ID_LENGTH) { + return false; + } + + for (int i = 0; i < length; i++) { + char c = str.charAt(i); + if ((c < '0') || (c > '9')) { + return false; + } + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(this.id, this.anchor); + } + + @Override + public boolean equals(Object o) { + + if (!(o instanceof Identifier that)) { + return false; + } + + return Objects.equals(this.id, that.id) && Objects.equals(this.anchor, that.anchor); + } + + @Override + public String toString() { + if (this.id != null) { + return this.id; + } + return this.anchor.toString(); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identity.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identity.java index 9024e82..b607c50 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identity.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Identity.java @@ -11,8 +11,5 @@ * authenticate themselves using different identity providers. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) -@JsonSubTypes({ - @JsonSubTypes.Type(value = LdapIdentity.class, name = "ldap") -}) -public interface Identity { -} +@JsonSubTypes({@JsonSubTypes.Type(value = LdapIdentity.class, name = "ldap")}) +public interface Identity {} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Role.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Role.java index c5e610c..e2b8335 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Role.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/Role.java @@ -1,12 +1,10 @@ package com.sitepark.ies.userrepository.core.domain.entity; -import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.sitepark.ies.userrepository.core.domain.entity.role.RoleDeserializer; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; /** * Defines user roles to manage permissions and access control @@ -16,44 +14,42 @@ @JsonDeserialize(using = RoleDeserializer.class) public class Role { - @JsonValue - private final String name; - - @SuppressFBWarnings("CT_CONSTRUCTOR_THROW") - protected Role(String name) { - Objects.requireNonNull(name, "name is null"); - if (name.isBlank()) { - throw new IllegalArgumentException("name is blank"); - } - this.name = name; - } - - public static Role ofName(String name) { - return new Role(name); - } - - public String getName() { - return this.name; - } - - @Override - public final int hashCode() { - return this.name != null ? this.name.hashCode() : 0; - } - - @Override - public final boolean equals(Object o) { - - if (!(o instanceof Role)) { - return false; - } - - Role other = (Role)o; - return Objects.equals(this.name, other.name); - } - - @Override - public String toString() { - return this.name; - } + @JsonValue private final String name; + + @SuppressFBWarnings("CT_CONSTRUCTOR_THROW") + protected Role(String name) { + Objects.requireNonNull(name, "name is null"); + if (name.isBlank()) { + throw new IllegalArgumentException("name is blank"); + } + this.name = name; + } + + public static Role ofName(String name) { + return new Role(name); + } + + public String getName() { + return this.name; + } + + @Override + public final int hashCode() { + return this.name != null ? this.name.hashCode() : 0; + } + + @Override + public final boolean equals(Object o) { + + if (!(o instanceof Role other)) { + return false; + } + + return Objects.equals(this.name, other.name); + } + + @Override + public String toString() { + return this.name; + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/User.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/User.java index fa2ac29..92beedd 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/User.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/User.java @@ -1,17 +1,15 @@ package com.sitepark.ies.userrepository.core.domain.entity; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; /** * Represents user @@ -19,356 +17,371 @@ @JsonDeserialize(builder = User.Builder.class) public final class User { - private final String id; - - private final Anchor anchor; - - private final String login; - - private final String firstname; - - private final String lastname; - - private final String email; - - private final GenderType gender; - - private final String note; - - private final UserValidity validity; - - private final List identityList; - - private final List roleList; - - protected User(Builder builder) { - this.id = builder.id; - this.anchor = builder.anchor; - this.login = builder.login; - this.firstname = builder.firstname; - this.lastname = builder.lastname; - this.email = builder.email; - this.gender = builder.gender; - this.note = builder.note; - this.validity = builder.validity; - this.identityList = builder.identityList; - this.roleList = Collections.unmodifiableList(builder.roleList); - } - - public Optional getId() { - if (this.id == null) { - return Optional.empty(); - } else { - return Optional.of(this.id); - } - } - - @JsonIgnore - public Optional getIdentifier() { - if (this.id != null) { - return Optional.of(Identifier.ofId(this.id)); - } - if (this.anchor != null) { - return Optional.of(Identifier.ofAnchor(this.anchor)); - } - return Optional.empty(); - } - - public Optional getAnchor() { - return Optional.ofNullable(this.anchor); - } - - public String getLogin() { - return this.login; - } - - @JsonIgnore - public String getName() { - StringBuilder name = new StringBuilder(); - if (this.lastname != null) { - name.append(this.lastname); - } - if (this.firstname != null) { - if (name.length() > 0) { - name.append(", "); - } - name.append(this.firstname); - } - return name.toString(); - } - - public Optional getFirstname() { - return Optional.ofNullable(this.firstname); - } - - public Optional getLastname() { - return Optional.ofNullable(this.lastname); - } - - public Optional getEmail() { - return Optional.ofNullable(this.email); - } - - public GenderType getGender() { - return this.gender; - } - - public Optional getNote() { - return Optional.ofNullable(this.note); - } - - public UserValidity getValidity() { - return this.validity; - } - - @SuppressFBWarnings("EI_EXPOSE_REP") - public List getIdentityList() { - return this.identityList; - } - - public Optional getIdentity(Class type) { - for (Identity identity : this.identityList) { - if (type.isInstance(identity)) { - return Optional.of(type.cast(identity)); - } - } - return Optional.empty(); - } - - @SuppressFBWarnings("EI_EXPOSE_REP") - public List getRoleList() { - return this.roleList; - } - - public static Builder builder() { - return new Builder(); - } - - public Builder toBuilder() { - return new Builder(this); - } - - @Override - public final int hashCode() { - return Objects.hash( - this.id, - this.anchor, - this.login, - this.firstname, - this.lastname, - this.email, - this.gender, - this.validity, - this.identityList, - this.note, - this.roleList); - } - - @Override - public final boolean equals(Object o) { - - if (!(o instanceof User)) { - return false; - } - - User entity = (User)o; - - return - Objects.equals(this.id, entity.id) && - Objects.equals(this.anchor, entity.anchor) && - Objects.equals(this.login, entity.login) && - Objects.equals(this.firstname, entity.firstname) && - Objects.equals(this.lastname, entity.lastname) && - Objects.equals(this.email, entity.email) && - Objects.equals(this.gender, entity.gender) && - Objects.equals(this.note, entity.note) && - Objects.equals(this.validity, entity.validity) && - Objects.equals(this.identityList, entity.identityList) && - Objects.equals(this.roleList, entity.roleList); - } - - @Override - public String toString() { - return "User [id=" + id + ", anchor=" + anchor + ", login=" + login + ", firstname=" + firstname + ", lastname=" - + lastname + ", email=" + email + ", gender=" + gender + ", note=" + note + ", validity=" + validity - + ", identityList=" + identityList + ", roleList=" + roleList + "]"; - } - - @SuppressWarnings("PMD.TooManyMethods") - @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") - public static final class Builder { - - private String id; - - private Anchor anchor; - - private String login; - - private String firstname; - - private String lastname; - - private String email; - - private GenderType gender = GenderType.UNKNOWN; - - private String note; - - private UserValidity validity = UserValidity.ALWAYS_VALID; - - private final List identityList = new ArrayList<>(); - - private final List roleList = new ArrayList<>(); - - protected Builder() { - } - - protected Builder(User user) { - this.id = user.id; - this.anchor = user.anchor; - this.login = user.login; - this.firstname = user.firstname; - this.lastname = user.lastname; - this.email = user.email; - this.gender = user.gender; - this.note = user.note; - this.validity = user.validity; - this.identityList.addAll(user.identityList); - this.roleList.addAll(user.roleList); - } - - public Builder id(String id) { - Objects.requireNonNull(id, "id is null"); - if (!Identifier.isId(id)) { - throw new IllegalArgumentException(id + " is not an id"); - } - this.id = id; - return this; - } - - public Builder identifier(Identifier identifier) { - if (identifier.getId().isPresent()) { - this.id = identifier.getId().get(); - return this; - } - this.anchor = identifier.getAnchor().get(); - return this; - } - - public Builder anchor(String anchor) { - this.anchor = Anchor.ofString(anchor); - return this; - } - - public Builder anchor(Anchor anchor) { - this.anchor = anchor; - return this; - } - - public Builder login(String login) { - this.login = this.trimToNull(login); - return this; - } - - public Builder firstname(String firstname) { - this.firstname = this.trimToNull(firstname); - return this; - } - - public Builder lastname(String lastname) { - this.lastname = this.trimToNull(lastname); - return this; - } - - public Builder email(String email) { - this.email = this.trimToNull(email); - return this; - } - - public Builder gender(GenderType gender) { - Objects.requireNonNull(gender, "gender is null"); - this.gender = gender; - return this; - } - - public Builder note(String note) { - this.note = this.trimToNull(note); - return this; - } - - public Builder validity(UserValidity.Builder validity) { - Objects.requireNonNull(validity, "validity is null"); - this.validity = validity.build(); - return this; - } - - @JsonSetter - public Builder validity(UserValidity validity) { - Objects.requireNonNull(validity, "validity is null"); - this.validity = validity; - return this; - } - - @JsonSetter - public Builder identityList(List identityList) { - Objects.requireNonNull(identityList, "identityList is null"); - this.identityList.clear(); - for (Identity identity : identityList) { - this.identity(identity); - } - return this; - } - - public Builder identityList(Identity... identityList) { - Objects.requireNonNull(identityList, "identityList is null"); - this.identityList.clear(); - for (Identity identity : identityList) { - this.identity(identity); - } - return this; - } - - public Builder identity(Identity identity) { - Objects.requireNonNull(identity, "identity is null"); - this.identityList.add(identity); - return this; - } - - @JsonSetter - public Builder roleList(Role... roleList) { - Objects.requireNonNull(roleList, "roleList is null"); - this.roleList.clear(); - for (Role role : roleList) { - this.role(role); - } - return this; - } - - public Builder roleList(List roleList) { - Objects.requireNonNull(roleList, "roleList is null"); - this.roleList.clear(); - for (Role role : roleList) { - this.role(role); - } - return this; - } - - public Builder role(Role role) { - Objects.requireNonNull(role, "role is null"); - this.roleList.add(role); - return this; - } - - public User build() { - if (this.login == null) { - throw new IllegalStateException("login is not set"); - } - return new User(this); - } - - @JsonIgnore - private String trimToNull(String str) { - return (str == null || str.isBlank()) ? null : str.trim(); - } - } + private final String id; + + private final Anchor anchor; + + private final String login; + + private final String firstname; + + private final String lastname; + + private final String email; + + private final GenderType gender; + + private final String note; + + private final UserValidity validity; + + private final List identityList; + + private final List roleList; + + protected User(Builder builder) { + this.id = builder.id; + this.anchor = builder.anchor; + this.login = builder.login; + this.firstname = builder.firstname; + this.lastname = builder.lastname; + this.email = builder.email; + this.gender = builder.gender; + this.note = builder.note; + this.validity = builder.validity; + this.identityList = builder.identityList; + this.roleList = Collections.unmodifiableList(builder.roleList); + } + + public Optional getId() { + if (this.id == null) { + return Optional.empty(); + } + return Optional.of(this.id); + } + + @JsonIgnore + public Optional getIdentifier() { + if (this.id != null) { + return Optional.of(Identifier.ofId(this.id)); + } + if (this.anchor != null) { + return Optional.of(Identifier.ofAnchor(this.anchor)); + } + return Optional.empty(); + } + + public Optional getAnchor() { + return Optional.ofNullable(this.anchor); + } + + public String getLogin() { + return this.login; + } + + @JsonIgnore + public String getName() { + StringBuilder name = new StringBuilder(); + if (this.lastname != null) { + name.append(this.lastname); + } + if (this.firstname != null) { + if (name.length() > 0) { + name.append(", "); + } + name.append(this.firstname); + } + return name.toString(); + } + + public Optional getFirstname() { + return Optional.ofNullable(this.firstname); + } + + public Optional getLastname() { + return Optional.ofNullable(this.lastname); + } + + public Optional getEmail() { + return Optional.ofNullable(this.email); + } + + public GenderType getGender() { + return this.gender; + } + + public Optional getNote() { + return Optional.ofNullable(this.note); + } + + public UserValidity getValidity() { + return this.validity; + } + + @SuppressFBWarnings("EI_EXPOSE_REP") + public List getIdentityList() { + return this.identityList; + } + + public Optional getIdentity(Class type) { + for (Identity identity : this.identityList) { + if (type.isInstance(identity)) { + return Optional.of(type.cast(identity)); + } + } + return Optional.empty(); + } + + @SuppressFBWarnings("EI_EXPOSE_REP") + public List getRoleList() { + return this.roleList; + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + @Override + public int hashCode() { + return Objects.hash( + this.id, + this.anchor, + this.login, + this.firstname, + this.lastname, + this.email, + this.gender, + this.validity, + this.identityList, + this.note, + this.roleList); + } + + @Override + public boolean equals(Object o) { + + if (!(o instanceof User entity)) { + return false; + } + + return Objects.equals(this.id, entity.id) + && Objects.equals(this.anchor, entity.anchor) + && Objects.equals(this.login, entity.login) + && Objects.equals(this.firstname, entity.firstname) + && Objects.equals(this.lastname, entity.lastname) + && Objects.equals(this.email, entity.email) + && Objects.equals(this.gender, entity.gender) + && Objects.equals(this.note, entity.note) + && Objects.equals(this.validity, entity.validity) + && Objects.equals(this.identityList, entity.identityList) + && Objects.equals(this.roleList, entity.roleList); + } + + @Override + public String toString() { + return "User [id=" + + this.id + + ", anchor=" + + this.anchor + + ", login=" + + this.login + + ", firstname=" + + this.firstname + + ", lastname=" + + this.lastname + + ", email=" + + this.email + + ", gender=" + + this.gender + + ", note=" + + this.note + + ", validity=" + + this.validity + + ", identityList=" + + this.identityList + + ", roleList=" + + this.roleList + + "]"; + } + + @SuppressWarnings("PMD.TooManyMethods") + @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") + public static final class Builder { + + private String id; + + private Anchor anchor; + + private String login; + + private String firstname; + + private String lastname; + + private String email; + + private GenderType gender = GenderType.UNKNOWN; + + private String note; + + private UserValidity validity = UserValidity.ALWAYS_VALID; + + private final List identityList = new ArrayList<>(); + + private final List roleList = new ArrayList<>(); + + protected Builder() {} + + protected Builder(User user) { + this.id = user.id; + this.anchor = user.anchor; + this.login = user.login; + this.firstname = user.firstname; + this.lastname = user.lastname; + this.email = user.email; + this.gender = user.gender; + this.note = user.note; + this.validity = user.validity; + this.identityList.addAll(user.identityList); + this.roleList.addAll(user.roleList); + } + + public Builder id(String id) { + Objects.requireNonNull(id, "id is null"); + if (!Identifier.isId(id)) { + throw new IllegalArgumentException(id + " is not an id"); + } + this.id = id; + return this; + } + + public Builder identifier(Identifier identifier) { + if (identifier.getId().isPresent()) { + this.id = identifier.getId().get(); + return this; + } + this.anchor = identifier.getAnchor().get(); + return this; + } + + public Builder anchor(String anchor) { + this.anchor = Anchor.ofString(anchor); + return this; + } + + public Builder anchor(Anchor anchor) { + this.anchor = anchor; + return this; + } + + public Builder login(String login) { + this.login = this.trimToNull(login); + return this; + } + + public Builder firstname(String firstname) { + this.firstname = this.trimToNull(firstname); + return this; + } + + public Builder lastname(String lastname) { + this.lastname = this.trimToNull(lastname); + return this; + } + + public Builder email(String email) { + this.email = this.trimToNull(email); + return this; + } + + public Builder gender(GenderType gender) { + Objects.requireNonNull(gender, "gender is null"); + this.gender = gender; + return this; + } + + public Builder note(String note) { + this.note = this.trimToNull(note); + return this; + } + + public Builder validity(UserValidity.Builder validity) { + Objects.requireNonNull(validity, "validity is null"); + this.validity = validity.build(); + return this; + } + + @JsonSetter + public Builder validity(UserValidity validity) { + Objects.requireNonNull(validity, "validity is null"); + this.validity = validity; + return this; + } + + @JsonSetter + public Builder identityList(List identityList) { + Objects.requireNonNull(identityList, "identityList is null"); + this.identityList.clear(); + for (Identity identity : identityList) { + this.identity(identity); + } + return this; + } + + public Builder identityList(Identity... identityList) { + Objects.requireNonNull(identityList, "identityList is null"); + this.identityList.clear(); + for (Identity identity : identityList) { + this.identity(identity); + } + return this; + } + + public Builder identity(Identity identity) { + Objects.requireNonNull(identity, "identity is null"); + this.identityList.add(identity); + return this; + } + + @JsonSetter + public Builder roleList(Role... roleList) { + Objects.requireNonNull(roleList, "roleList is null"); + this.roleList.clear(); + for (Role role : roleList) { + this.role(role); + } + return this; + } + + public Builder roleList(List roleList) { + Objects.requireNonNull(roleList, "roleList is null"); + this.roleList.clear(); + for (Role role : roleList) { + this.role(role); + } + return this; + } + + public Builder role(Role role) { + Objects.requireNonNull(role, "role is null"); + this.roleList.add(role); + return this; + } + + public User build() { + if (this.login == null) { + throw new IllegalStateException("login is not set"); + } + return new User(this); + } + + @JsonIgnore + private String trimToNull(String str) { + return ((str == null) || str.isBlank()) ? null : str.trim(); + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidity.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidity.java index e9aa3a3..16ea08a 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidity.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidity.java @@ -1,12 +1,11 @@ package com.sitepark.ies.userrepository.core.domain.entity; -import java.time.OffsetDateTime; -import java.util.Objects; -import java.util.Optional; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; /** * Encapsulates user properties indicating whether a user @@ -15,142 +14,136 @@ @JsonDeserialize(builder = UserValidity.Builder.class) public class UserValidity { - private final boolean blocked; - - private final OffsetDateTime validFrom; - - private final OffsetDateTime validTo; - - public static final UserValidity ALWAYS_VALID = UserValidity.builder().blocked(false).build(); - - protected UserValidity(Builder builder) { - this.blocked = builder.blocked; - this.validFrom = builder.validFrom; - this.validTo = builder.validTo; - } - - public boolean isBlocked() { - return this.blocked; - } - - public Optional getValidFrom() { - return Optional.ofNullable(this.validFrom); - } - - public Optional getValidTo() { - return Optional.ofNullable(this.validTo); - } - - @JsonIgnore - @SuppressWarnings("PMD.SimplifyBooleanReturns") - public boolean isValid(OffsetDateTime base) { + private final boolean blocked; - Objects.requireNonNull(base, "base is null"); + private final OffsetDateTime validFrom; - if (this.blocked) { - return false; - } + private final OffsetDateTime validTo; - if (this.validFrom != null && this.validFrom.isAfter(base)) { - return false; - } + public static final UserValidity ALWAYS_VALID = UserValidity.builder().blocked(false).build(); - if (this.validTo != null && this.validTo.isBefore(base)) { - return false; - } + protected UserValidity(Builder builder) { + this.blocked = builder.blocked; + this.validFrom = builder.validFrom; + this.validTo = builder.validTo; + } - return true; - } + public boolean isBlocked() { + return this.blocked; + } - @JsonIgnore - public boolean isNowValid() { - return this.isValid(OffsetDateTime.now()); - } + public Optional getValidFrom() { + return Optional.ofNullable(this.validFrom); + } - public static Builder builder() { - return new Builder(); - } + public Optional getValidTo() { + return Optional.ofNullable(this.validTo); + } - public Builder toBuilder() { - return new Builder(this); - } + @JsonIgnore + @SuppressWarnings("PMD.SimplifyBooleanReturns") + public boolean isValid(OffsetDateTime base) { - @Override - public final int hashCode() { + Objects.requireNonNull(base, "base is null"); - int hash = Boolean.hashCode(this.blocked); - hash = (this.validFrom != null) ? 31 * hash + this.validFrom.hashCode() : hash; - hash = (this.validTo != null) ? 31 * hash + this.validTo.hashCode() : hash; + if (this.blocked || ((this.validFrom != null) && this.validFrom.isAfter(base))) { + return false; + } - return hash; - } + if ((this.validTo != null) && this.validTo.isBefore(base)) { + return false; + } - @Override - @SuppressWarnings({ - "PMD.CyclomaticComplexity", - "PMD.NPathComplexity" - }) - public final boolean equals(Object o) { + return true; + } - if (!(o instanceof UserValidity)) { - return false; - } + @JsonIgnore + public boolean isNowValid() { + return this.isValid(OffsetDateTime.now()); + } - UserValidity validity = (UserValidity)o; + public static Builder builder() { + return new Builder(); + } - if (!Objects.equals(this.blocked, validity.blocked)) { - return false; - } else if (!Objects.equals(this.validFrom, validity.validFrom)) { - return false; - } else if (!Objects.equals(this.validTo, validity.validTo)) { - return false; - } + public Builder toBuilder() { + return new Builder(this); + } - return true; - } + @Override + public final int hashCode() { - @Override - public String toString() { - return "UserValidity [blocked=" + blocked + ", validFrom=" + validFrom + ", validTo=" + validTo + "]"; - } + int hash = Boolean.hashCode(this.blocked); + hash = (this.validFrom != null) ? (31 * hash) + this.validFrom.hashCode() : hash; + return (this.validTo != null) ? (31 * hash) + this.validTo.hashCode() : hash; + } - @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") - public static final class Builder { + @Override + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.NPathComplexity"}) + public final boolean equals(Object o) { - private boolean blocked; + if (!(o instanceof UserValidity validity)) { + return false; + } - private OffsetDateTime validFrom; + if (!Objects.equals(this.blocked, validity.blocked)) { + return false; + } + if (!Objects.equals(this.validFrom, validity.validFrom) + || !Objects.equals(this.validTo, validity.validTo)) { + return false; + } - private OffsetDateTime validTo; + return true; + } - protected Builder() { - } - - protected Builder(UserValidity userValidity) { - this.blocked = userValidity.blocked; - this.validFrom = userValidity.validFrom; - this.validTo = userValidity.validTo; - } + @Override + public String toString() { + return "UserValidity [blocked=" + + this.blocked + + ", validFrom=" + + this.validFrom + + ", validTo=" + + this.validTo + + "]"; + } - public Builder blocked(boolean blocked) { - this.blocked = blocked; - return this; - } + @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") + public static final class Builder { - public Builder validFrom(OffsetDateTime validFrom) { - Objects.requireNonNull(validFrom, "validFrom is null"); - this.validFrom = validFrom; - return this; - } + private boolean blocked; - public Builder validTo(OffsetDateTime validTo) { - Objects.requireNonNull(validTo, "validTo is null"); - this.validTo = validTo; - return this; - } - - public UserValidity build() { - return new UserValidity(this); - } - } + private OffsetDateTime validFrom; + + private OffsetDateTime validTo; + + protected Builder() {} + + protected Builder(UserValidity userValidity) { + this.blocked = userValidity.blocked; + this.validFrom = userValidity.validFrom; + this.validTo = userValidity.validTo; + } + + public Builder blocked(boolean blocked) { + this.blocked = blocked; + return this; + } + + public Builder validFrom(OffsetDateTime validFrom) { + Objects.requireNonNull(validFrom, "validFrom is null"); + this.validFrom = validFrom; + return this; + } + + public Builder validTo(OffsetDateTime validTo) { + Objects.requireNonNull(validTo, "validTo is null"); + this.validTo = validTo; + return this; + } + + public UserValidity build() { + return new UserValidity(this); + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentity.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentity.java index c11f8c6..959fe14 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentity.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentity.java @@ -1,10 +1,9 @@ package com.sitepark.ies.userrepository.core.domain.entity.identity; -import java.util.Objects; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.sitepark.ies.userrepository.core.domain.entity.Identity; +import java.util.Objects; /** * The LdapIdentity class represents an identity provider using @@ -14,100 +13,96 @@ @JsonDeserialize(builder = LdapIdentity.Builder.class) public final class LdapIdentity implements Identity { - private final int server; - - private final String dn; - - private LdapIdentity(Builder builder) { - this.server = builder.server; - this.dn = builder.dn; - } - - public int getServer() { - return this.server; - } - - public String getDn() { - return this.dn; - } - - public static Builder builder() { - return new Builder(); - } - - public Builder toBuilder() { - return new Builder(this); - } - - @Override - public final int hashCode() { - int hash = this.server; - hash = (this.dn != null) ? 31 * hash + this.dn.hashCode() : hash; - return hash; - } - - @Override - public String toString() { - return "LdapIdentity [server=" + server + ", dn=" + dn + "]"; - } - - @Override - public final boolean equals(Object o) { - - if (!(o instanceof LdapIdentity)) { - return false; - } - - LdapIdentity entity = (LdapIdentity)o; - - if (this.server != entity.server) { - return false; - } else if (!Objects.equals(this.dn, entity.dn)) { - return false; - } - - return true; - } - @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") - public static final class Builder { - - private int server; - - private String dn; - - private Builder() {} - - public Builder(LdapIdentity ldapIdentity) { - this.server = ldapIdentity.server; - this.dn = ldapIdentity.dn; - } - - public Builder server(int server) { - if (server <= 0) { - throw new IllegalArgumentException("server should be greater then 0"); - } - this.server = server; - return this; - } - - public Builder dn(String dn) { - Objects.requireNonNull(dn, "dn is null"); - if (dn.isBlank()) { - throw new IllegalArgumentException("dn should not be blank"); - } - this.dn = dn; - return this; - } - - public LdapIdentity build() { - - if (this.server == 0) { - throw new IllegalStateException("server is not set"); - } - if (this.dn == null) { - throw new IllegalStateException("dn is not set"); - } - return new LdapIdentity(this); - } - } + private final int server; + + private final String dn; + + private LdapIdentity(Builder builder) { + this.server = builder.server; + this.dn = builder.dn; + } + + public int getServer() { + return this.server; + } + + public String getDn() { + return this.dn; + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + @Override + public int hashCode() { + int hash = this.server; + return (this.dn != null) ? (31 * hash) + this.dn.hashCode() : hash; + } + + @Override + public String toString() { + return "LdapIdentity [server=" + this.server + ", dn=" + this.dn + "]"; + } + + @Override + public boolean equals(Object o) { + + if (!(o instanceof LdapIdentity entity)) { + return false; + } + + if ((this.server != entity.server) || !Objects.equals(this.dn, entity.dn)) { + return false; + } + + return true; + } + + @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build") + public static final class Builder { + + private int server; + + private String dn; + + private Builder() {} + + public Builder(LdapIdentity ldapIdentity) { + this.server = ldapIdentity.server; + this.dn = ldapIdentity.dn; + } + + public Builder server(int server) { + if (server <= 0) { + throw new IllegalArgumentException("server should be greater then 0"); + } + this.server = server; + return this; + } + + public Builder dn(String dn) { + Objects.requireNonNull(dn, "dn is null"); + if (dn.isBlank()) { + throw new IllegalArgumentException("dn should not be blank"); + } + this.dn = dn; + return this; + } + + public LdapIdentity build() { + + if (this.server == 0) { + throw new IllegalStateException("server is not set"); + } + if (this.dn == null) { + throw new IllegalStateException("dn is not set"); + } + return new LdapIdentity(this); + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/Ref.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/Ref.java index 2a78de2..9f959e3 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/Ref.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/Ref.java @@ -1,11 +1,10 @@ package com.sitepark.ies.userrepository.core.domain.entity.role; -import java.util.Objects; -import java.util.Optional; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.entity.Role; +import java.util.Objects; +import java.util.Optional; /** * Represents a role that references a group, @@ -15,64 +14,64 @@ @SuppressWarnings("PMD.CommentSize") public final class Ref extends Role { - private final String id; + private final String id; - private final Anchor anchor; + private final Anchor anchor; - /** - * For object mapping with myBatis an objectfactory is used. - * However, this only takes effect if a default constructor exists. - * @see - * DefaultResultSetHandler.java - * - * - */ - @SuppressWarnings("PMD.NullAssignment") - protected Ref() { - super("NONE"); - this.id = null; - this.anchor = null; - } + /** + * For object mapping with myBatis an objectfactory is used. + * However, this only takes effect if a default constructor exists. + * @see + * DefaultResultSetHandler.java + * + * + */ + @SuppressWarnings("PMD.NullAssignment") + protected Ref() { + super("NONE"); + this.id = null; + this.anchor = null; + } - // A ref has either an id or an anchor. - @SuppressWarnings("PMD.NullAssignment") - private Ref(String id) { - super("REF(" + id + ")"); - if (!Identifier.isId(id)) { - throw new IllegalArgumentException(id + " not an id"); - } - this.id = id; - this.anchor = null; - } + // A ref has either an id or an anchor. + @SuppressWarnings("PMD.NullAssignment") + private Ref(String id) { + super("REF(" + id + ")"); + if (!Identifier.isId(id)) { + throw new IllegalArgumentException(id + " not an id"); + } + this.id = id; + this.anchor = null; + } - private Ref(Anchor anchor) { - super("REF(" + anchor + ")"); - Objects.requireNonNull(anchor, "anchor is null"); - this.id = null; - this.anchor = anchor; - } + private Ref(Anchor anchor) { + super("REF(" + anchor + ")"); + Objects.requireNonNull(anchor, "anchor is null"); + this.id = null; + this.anchor = anchor; + } - public static Ref ofId(String id) { - return new Ref(id); - } + public static Ref ofId(String id) { + return new Ref(id); + } - public static Ref ofAnchor(Anchor anchor) { - return new Ref(anchor); - } + public static Ref ofAnchor(Anchor anchor) { + return new Ref(anchor); + } - public static Ref ofAnchor(String anchor) { - Objects.requireNonNull(anchor, "anchor is null"); - return new Ref(Anchor.ofString(anchor)); - } + public static Ref ofAnchor(String anchor) { + Objects.requireNonNull(anchor, "anchor is null"); + return new Ref(Anchor.ofString(anchor)); + } - public Optional getId() { - if (this.id == null) { - return Optional.empty(); - } - return Optional.of(this.id); - } + public Optional getId() { + if (this.id == null) { + return Optional.empty(); + } + return Optional.of(this.id); + } - public Optional getAnchor() { - return Optional.ofNullable(this.anchor); - } + public Optional getAnchor() { + return Optional.ofNullable(this.anchor); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactory.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactory.java index 53ad991..7d62882 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactory.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactory.java @@ -1,10 +1,9 @@ package com.sitepark.ies.userrepository.core.domain.entity.role; +import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.sitepark.ies.userrepository.core.domain.entity.Anchor; - /** * The RefFactory class is responsible for creating {@link Ref} objects, * which can reference a group using either an {@link Anchor} or an ID as a reference. @@ -15,34 +14,33 @@ */ public class RefFactory implements RoleFactory { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private static final Pattern PATTERN_ID = Pattern.compile("^REF\\(([0-9]+)\\)$"); + private static final Pattern PATTERN_ID = Pattern.compile("^REF\\(([0-9]+)\\)$"); - private static final Pattern PATTERN_ANCHOR = Pattern.compile("^REF\\((" + Anchor.VALID_CHARS_REGEX + ")\\)$"); + private static final Pattern PATTERN_ANCHOR = + Pattern.compile("^REF\\((" + Anchor.VALID_CHARS_REGEX + ")\\)$"); - @Override - public boolean accept(String role) { - return - PATTERN_ID.matcher(role).matches() || - PATTERN_ANCHOR.matcher(role).matches(); - } + @Override + public boolean accept(String role) { + return PATTERN_ID.matcher(role).matches() || PATTERN_ANCHOR.matcher(role).matches(); + } - @Override - public Ref create(String role) { + @Override + public Ref create(String role) { - Matcher idMatcher = PATTERN_ID.matcher(role); - if (idMatcher.matches()) { - String id = idMatcher.group(1); - return Ref.ofId(id); - } + Matcher idMatcher = PATTERN_ID.matcher(role); + if (idMatcher.matches()) { + String id = idMatcher.group(1); + return Ref.ofId(id); + } - Matcher anchorMatcher = PATTERN_ANCHOR.matcher(role); - if (anchorMatcher.matches()) { - String anchor = anchorMatcher.group(1); - return Ref.ofAnchor(anchor); - } + Matcher anchorMatcher = PATTERN_ANCHOR.matcher(role); + if (anchorMatcher.matches()) { + String anchor = anchorMatcher.group(1); + return Ref.ofAnchor(anchor); + } - throw new IllegalArgumentException("Invalid role: " + role); - } + throw new IllegalArgumentException("Invalid role: " + role); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleDeserializer.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleDeserializer.java index 63ee9a3..ac9fcd6 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleDeserializer.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleDeserializer.java @@ -1,12 +1,11 @@ package com.sitepark.ies.userrepository.core.domain.entity.role; -import java.io.IOException; - import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.sitepark.ies.userrepository.core.domain.entity.Role; +import java.io.IOException; /** * The RoleDeserializer is a custom Jackson deserializer responsible for @@ -18,21 +17,21 @@ */ public class RoleDeserializer extends StdDeserializer { - private static final long serialVersionUID = 1L; - - private static final RefFactory REF_FACTORY = new RefFactory(); + private static final long serialVersionUID = 1L; - protected RoleDeserializer() { - super(Role.class); - } + private static final RefFactory REF_FACTORY = new RefFactory(); - @Override - public Role deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException { - String s = p.readValueAs(String.class); - if (REF_FACTORY.accept(s)) { - return REF_FACTORY.create(s); - } - return Role.ofName(s); - } + protected RoleDeserializer() { + super(Role.class); + } + @Override + public Role deserialize(JsonParser p, DeserializationContext ctxt) + throws IOException, JacksonException { + String s = p.readValueAs(String.class); + if (REF_FACTORY.accept(s)) { + return REF_FACTORY.create(s); + } + return Role.ofName(s); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleFactory.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleFactory.java index b732780..07c0663 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleFactory.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/RoleFactory.java @@ -1,8 +1,7 @@ package com.sitepark.ies.userrepository.core.domain.entity.role; -import java.io.Serializable; - import com.sitepark.ies.userrepository.core.domain.entity.Role; +import java.io.Serializable; /** * The RoleFactory interface defines the contract for classes @@ -11,6 +10,7 @@ * and managing roles within the system. */ public interface RoleFactory extends Serializable { - boolean accept(String role); - Role create(String role); + boolean accept(String role); + + Role create(String role); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRoles.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRoles.java index 523aa40..f962062 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRoles.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRoles.java @@ -9,32 +9,29 @@ */ public final class UserLevelRoles { - /** - * The ADMINISTRATOR role represents a user with - * full system access, allowing complete control and administration - * of the application. - */ - public static final Role ADMINISTRATOR = Role.ofName("ADMINISTRATOR"); + /** + * The ADMINISTRATOR role represents a user with + * full system access, allowing complete control and administration + * of the application. + */ + public static final Role ADMINISTRATOR = Role.ofName("ADMINISTRATOR"); - /** - * The USER role represents a standard user, and - * their roles define their access permissions within the system. - */ - public static final Role USER = Role.ofName("USER"); + /** + * The USER role represents a standard user, and + * their roles define their access permissions within the system. + */ + public static final Role USER = Role.ofName("USER"); - /** - * The EXTERNAL role represents users marked as external, - * subject to certain limitations. These users are restricted from - * accessing backend applications. - */ - public static final Role EXTERNAL = Role.ofName("EXTERNAL"); + /** + * The EXTERNAL role represents users marked as external, + * subject to certain limitations. These users are restricted from + * accessing backend applications. + */ + public static final Role EXTERNAL = Role.ofName("EXTERNAL"); - private UserLevelRoles() {} + private UserLevelRoles() {} - public static boolean isUserLevelRole(Role role) { - return - ADMINISTRATOR.equals(role) || - USER.equals(role) || - EXTERNAL.equals(role); - } + public static boolean isUserLevelRole(Role role) { + return ADMINISTRATOR.equals(role) || USER.equals(role) || EXTERNAL.equals(role); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessDeniedException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessDeniedException.java index 843b5ee..53356df 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessDeniedException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessDeniedException.java @@ -6,9 +6,9 @@ * insufficient permissions or authorization. */ public class AccessDeniedException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AccessDeniedException(String message) { - super(message); - } -} \ No newline at end of file + public AccessDeniedException(String message) { + super(message); + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenDegistException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenDegistException.java index e29ccb6..4b2f850 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenDegistException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenDegistException.java @@ -6,13 +6,13 @@ */ public class AccessTokenDegistException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AccessTokenDegistException(String message) { - super(message); - } + public AccessTokenDegistException(String message) { + super(message); + } - public AccessTokenDegistException(String message, Throwable t) { - super(message, t); - } -} \ No newline at end of file + public AccessTokenDegistException(String message, Throwable t) { + super(message, t); + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenExpiredException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenExpiredException.java index c709ff0..db1552e 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenExpiredException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenExpiredException.java @@ -9,22 +9,20 @@ */ public class AccessTokenExpiredException extends AuthenticationFailedException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final OffsetDateTime expiredAt; + private final OffsetDateTime expiredAt; - public AccessTokenExpiredException(OffsetDateTime expiredAt) { - super(); - this.expiredAt = expiredAt; - } + public AccessTokenExpiredException(OffsetDateTime expiredAt) { + this.expiredAt = expiredAt; + } - public OffsetDateTime getExpiredAt() { - return this.expiredAt; - } + public OffsetDateTime getExpiredAt() { + return this.expiredAt; + } - @Override - public String getMessage() { - return "Token has expired since " + this.expiredAt; - } - -} \ No newline at end of file + @Override + public String getMessage() { + return "Token has expired since " + this.expiredAt; + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenNotActiveException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenNotActiveException.java index 4711a9a..6e17d29 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenNotActiveException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenNotActiveException.java @@ -7,9 +7,7 @@ */ public class AccessTokenNotActiveException extends AuthenticationFailedException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AccessTokenNotActiveException() { - super(); - } -} \ No newline at end of file + public AccessTokenNotActiveException() {} +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenRevokedException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenRevokedException.java index c3056ca..95d8aac 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenRevokedException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AccessTokenRevokedException.java @@ -6,9 +6,7 @@ */ public class AccessTokenRevokedException extends AuthenticationFailedException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AccessTokenRevokedException() { - super(); - } -} \ No newline at end of file + public AccessTokenRevokedException() {} +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorAlreadyExistsException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorAlreadyExistsException.java index 8dfeb30..83d7e98 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorAlreadyExistsException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorAlreadyExistsException.java @@ -8,29 +8,27 @@ */ public class AnchorAlreadyExistsException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final Anchor anchor; + private final Anchor anchor; - private final String owner; + private final String owner; - public AnchorAlreadyExistsException(Anchor anchor, String owner) { - super(); - this.anchor = anchor; - this.owner = owner; - } + public AnchorAlreadyExistsException(Anchor anchor, String owner) { + this.anchor = anchor; + this.owner = owner; + } - public Anchor getAnchor() { - return this.anchor; - } + public Anchor getAnchor() { + return this.anchor; + } - public String getOwner() { - return this.owner; - } - - @Override - public String getMessage() { - return "Anchor " + this.anchor + " already exists for user " + this.owner; - } + public String getOwner() { + return this.owner; + } + @Override + public String getMessage() { + return "Anchor " + this.anchor + " already exists for user " + this.owner; + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundException.java index 5c07c97..a867525 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundException.java @@ -9,21 +9,20 @@ */ public class AnchorNotFoundException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final Anchor anchor; + private final Anchor anchor; - public AnchorNotFoundException(Anchor anchor) { - super(); - this.anchor = anchor; - } + public AnchorNotFoundException(Anchor anchor) { + this.anchor = anchor; + } - public Anchor getAnchor() { - return this.anchor; - } + public Anchor getAnchor() { + return this.anchor; + } - @Override - public String getMessage() { - return "User with anchor " + this.anchor + " not found"; - } -} \ No newline at end of file + @Override + public String getMessage() { + return "User with anchor " + this.anchor + " not found"; + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AuthenticationFailedException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AuthenticationFailedException.java index 206bfde..6c604b4 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AuthenticationFailedException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/AuthenticationFailedException.java @@ -6,14 +6,11 @@ * was unsuccessful for some reason. */ public abstract class AuthenticationFailedException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AuthenticationFailedException() { - super(); - } + public AuthenticationFailedException() {} - public AuthenticationFailedException(String msg) { - super(msg); - } - -} \ No newline at end of file + public AuthenticationFailedException(String msg) { + super(msg); + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAccessTokenException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAccessTokenException.java index 20bdc72..73dfe9a 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAccessTokenException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAccessTokenException.java @@ -6,9 +6,9 @@ */ public class InvalidAccessTokenException extends AuthenticationFailedException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public InvalidAccessTokenException(String msg) { - super(msg); - } -} \ No newline at end of file + public InvalidAccessTokenException(String msg) { + super(msg); + } +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAnchorException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAnchorException.java index 35c7b7c..69c236f 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAnchorException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/InvalidAnchorException.java @@ -6,22 +6,23 @@ */ public class InvalidAnchorException extends UserRepositoryException { - private final String name; + private final String name; - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public InvalidAnchorException(String name, String message) { - super(message); - this.name = name; - } + public InvalidAnchorException(String name, String message) { + super(message); + this.name = name; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - @Override - public String getMessage() { - return "Invalid anchor '" + this.name + - (super.getMessage() != null ? ": " + super.getMessage() : ""); - } + @Override + public String getMessage() { + return "Invalid anchor '" + + this.name + + (super.getMessage() != null ? ": " + super.getMessage() : ""); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/LoginAlreadyExistsException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/LoginAlreadyExistsException.java index 9f13b2b..771b92b 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/LoginAlreadyExistsException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/LoginAlreadyExistsException.java @@ -7,29 +7,27 @@ */ public class LoginAlreadyExistsException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final String login; + private final String login; - private final String owner; + private final String owner; - public LoginAlreadyExistsException(String login, String owner) { - super(); - this.login = login; - this.owner = owner; - } + public LoginAlreadyExistsException(String login, String owner) { + this.login = login; + this.owner = owner; + } - public String getLogin() { - return this.login; - } + public String getLogin() { + return this.login; + } - public String getOwner() { - return this.owner; - } - - @Override - public String getMessage() { - return "Login " + this.login + " already exists for user " + this.owner; - } + public String getOwner() { + return this.owner; + } + @Override + public String getMessage() { + return "Login " + this.login + " already exists for user " + this.owner; + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserNotFoundException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserNotFoundException.java index 1afeb1d..1640951 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserNotFoundException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserNotFoundException.java @@ -7,21 +7,20 @@ */ public class UserNotFoundException extends UserRepositoryException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final String id; + private final String id; - public UserNotFoundException(String id) { - super(); - this.id = id; - } + public UserNotFoundException(String id) { + this.id = id; + } - public String getId() { - return this.id; - } + public String getId() { + return this.id; + } - @Override - public String getMessage() { - return "User with id " + this.id + " not found"; - } + @Override + public String getMessage() { + return "User with id " + this.id + " not found"; + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserRepositoryException.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserRepositoryException.java index 9778d9d..d7c8e88 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserRepositoryException.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/exception/UserRepositoryException.java @@ -7,15 +7,15 @@ */ public abstract class UserRepositoryException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public UserRepositoryException() { - super(); - } - public UserRepositoryException(String message) { - super(message); - } - public UserRepositoryException(String message, Throwable t) { - super(message, t); - } + public UserRepositoryException() {} + + public UserRepositoryException(String message) { + super(message); + } + + public UserRepositoryException(String message, Throwable t) { + super(message, t); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolver.java b/src/main/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolver.java index 3acf202..53b476b 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolver.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolver.java @@ -1,32 +1,30 @@ package com.sitepark.ies.userrepository.core.domain.service; -import java.util.Optional; - -import jakarta.inject.Inject; - import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.exception.AnchorNotFoundException; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import java.util.Optional; public class IdentifierResolver { - private final UserRepository repository; + private final UserRepository repository; - @Inject - protected IdentifierResolver(UserRepository repository) { - this.repository = repository; - } + @Inject + protected IdentifierResolver(UserRepository repository) { + this.repository = repository; + } - public String resolveIdentifier(Identifier identifier) { + public String resolveIdentifier(Identifier identifier) { - if (identifier.getId().isPresent()) { - return identifier.getId().get(); - } + if (identifier.getId().isPresent()) { + return identifier.getId().get(); + } - Optional id = this.repository.resolveAnchor(identifier.getAnchor().get()); - if (id.isEmpty()) { - throw new AnchorNotFoundException(identifier.getAnchor().get()); - } - return id.get(); - } + Optional id = this.repository.resolveAnchor(identifier.getAnchor().get()); + if (id.isEmpty()) { + throw new AnchorNotFoundException(identifier.getAnchor().get()); + } + return id.get(); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/AccessControl.java b/src/main/java/com/sitepark/ies/userrepository/core/port/AccessControl.java index a1c1cb1..8d320f8 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/AccessControl.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/AccessControl.java @@ -1,9 +1,13 @@ package com.sitepark.ies.userrepository.core.port; public interface AccessControl { - boolean isImpersonationTokensManageable(); - boolean isUserCreateable(); - boolean isUserReadable(String id); - boolean isUserWritable(String id); - boolean isUserRemovable(String id); + boolean isImpersonationTokensManageable(); + + boolean isUserCreateable(); + + boolean isUserReadable(String id); + + boolean isUserWritable(String id); + + boolean isUserRemovable(String id); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/AccessTokenRepository.java b/src/main/java/com/sitepark/ies/userrepository/core/port/AccessTokenRepository.java index 3b8be3b..fb51d33 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/AccessTokenRepository.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/AccessTokenRepository.java @@ -1,20 +1,19 @@ package com.sitepark.ies.userrepository.core.port; -import java.util.Optional; - import com.sitepark.ies.userrepository.core.domain.entity.AccessToken; +import java.util.Optional; public interface AccessTokenRepository { - AccessToken create(AccessToken accessToken); + AccessToken create(AccessToken accessToken); - void revoke(String user, String id); + void revoke(String user, String id); - void purge(String user, String id); + void purge(String user, String id); - void purgeByUser(String user); + void purgeByUser(String user); - void touch(String user, String id); + void touch(String user, String id); - Optional getByToken(String token); + Optional getByToken(String token); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/ExtensionsNotifier.java b/src/main/java/com/sitepark/ies/userrepository/core/port/ExtensionsNotifier.java index 60f08a5..cff0c93 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/ExtensionsNotifier.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/ExtensionsNotifier.java @@ -3,7 +3,9 @@ import com.sitepark.ies.userrepository.core.domain.entity.User; public interface ExtensionsNotifier { - void notifyPurge(String id); - void notifyCreated(User user); - void notifyUpdated(User user); + void notifyPurge(String id); + + void notifyCreated(User user); + + void notifyUpdated(User user); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/IdGenerator.java b/src/main/java/com/sitepark/ies/userrepository/core/port/IdGenerator.java index afe265d..77fd6f7 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/IdGenerator.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/IdGenerator.java @@ -1,5 +1,5 @@ package com.sitepark.ies.userrepository.core.port; public interface IdGenerator { - String generate(); + String generate(); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/RoleAssigner.java b/src/main/java/com/sitepark/ies/userrepository/core/port/RoleAssigner.java index 13cba4d..71a0d6e 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/RoleAssigner.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/RoleAssigner.java @@ -1,21 +1,19 @@ package com.sitepark.ies.userrepository.core.port; -import java.util.List; - import com.sitepark.ies.userrepository.core.domain.entity.Role; +import java.util.List; public interface RoleAssigner { - void assignRoleToUser(List roleList, List userList); - - void reassignRoleToUser(List roleList, List userList); + void assignRoleToUser(List roleList, List userList); - void revokeRoleFromUser(List roleList, List userList); + void reassignRoleToUser(List roleList, List userList); - void revokeAllRolesFromUser(List userList); + void revokeRoleFromUser(List roleList, List userList); - List getRolesAssignByUser(String id); + void revokeAllRolesFromUser(List userList); - List getUserAssignByRole(Role role); + List getRolesAssignByUser(String id); -} \ No newline at end of file + List getUserAssignByRole(Role role); +} diff --git a/src/main/java/com/sitepark/ies/userrepository/core/port/UserRepository.java b/src/main/java/com/sitepark/ies/userrepository/core/port/UserRepository.java index 0a90248..be19e30 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/port/UserRepository.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/port/UserRepository.java @@ -1,15 +1,19 @@ package com.sitepark.ies.userrepository.core.port; -import java.util.Optional; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import com.sitepark.ies.userrepository.core.domain.entity.User; +import java.util.Optional; public interface UserRepository { - void create(User entity); - void update(User entity); - Optional get(String id); - void remove(String id); - Optional resolveLogin(String login); - Optional resolveAnchor(Anchor anchor); + void create(User entity); + + void update(User entity); + + Optional get(String id); + + void remove(String id); + + Optional resolveLogin(String login); + + Optional resolveAnchor(Anchor anchor); } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByToken.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByToken.java index 1d97a41..e246177 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByToken.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByToken.java @@ -1,10 +1,5 @@ package com.sitepark.ies.userrepository.core.usecase; -import java.time.OffsetDateTime; -import java.util.Optional; - -import jakarta.inject.Inject; - import com.sitepark.ies.userrepository.core.domain.entity.AccessToken; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessTokenExpiredException; @@ -13,54 +8,56 @@ import com.sitepark.ies.userrepository.core.domain.exception.InvalidAccessTokenException; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import java.time.OffsetDateTime; +import java.util.Optional; public class AuthenticateByToken { - private final AccessTokenRepository accessTokenRepository; + private final AccessTokenRepository accessTokenRepository; - private final UserRepository userRepository; + private final UserRepository userRepository; - @Inject - protected AuthenticateByToken( - AccessTokenRepository accessTokenRepository, - UserRepository userRepository) { - this.accessTokenRepository = accessTokenRepository; - this.userRepository = userRepository; - } + @Inject + protected AuthenticateByToken( + AccessTokenRepository accessTokenRepository, UserRepository userRepository) { + this.accessTokenRepository = accessTokenRepository; + this.userRepository = userRepository; + } - public User authenticateByToken(String token) { + public User authenticateByToken(String token) { - Optional accessTokenOptinal = this.accessTokenRepository.getByToken(token); - if (accessTokenOptinal.isEmpty()) { - throw new InvalidAccessTokenException("Token not found"); - } + Optional accessTokenOptinal = this.accessTokenRepository.getByToken(token); + if (accessTokenOptinal.isEmpty()) { + throw new InvalidAccessTokenException("Token not found"); + } - AccessToken accessToken = accessTokenOptinal.get(); - if (!accessToken.isActive()) { - throw new AccessTokenNotActiveException(); - } - if (accessToken.isRevoked()) { - throw new AccessTokenRevokedException(); - } - this.checkExpirationDate(accessToken.getExpiresAt()); + AccessToken accessToken = accessTokenOptinal.get(); + if (!accessToken.isActive()) { + throw new AccessTokenNotActiveException(); + } + if (accessToken.isRevoked()) { + throw new AccessTokenRevokedException(); + } + this.checkExpirationDate(accessToken.getExpiresAt()); - Optional user = this.userRepository.get(accessToken.getUser()); - if (user.isEmpty()) { - throw new InvalidAccessTokenException("User " + accessToken.getUser() + " not found"); - } + Optional user = this.userRepository.get(accessToken.getUser()); + if (user.isEmpty()) { + throw new InvalidAccessTokenException("User " + accessToken.getUser() + " not found"); + } - return user.get(); - } + return user.get(); + } - public void checkExpirationDate(Optional expiredAt) { + public void checkExpirationDate(Optional expiredAt) { - if (expiredAt.isEmpty()) { - return; - } + if (expiredAt.isEmpty()) { + return; + } - OffsetDateTime now = OffsetDateTime.now(); - if (expiredAt.get().isBefore(now)) { - throw new AccessTokenExpiredException(expiredAt.get()); - } - } + OffsetDateTime now = OffsetDateTime.now(); + if (expiredAt.get().isBefore(now)) { + throw new AccessTokenExpiredException(expiredAt.get()); + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationToken.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationToken.java index 96c30b8..f649196 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationToken.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationToken.java @@ -1,55 +1,51 @@ package com.sitepark.ies.userrepository.core.usecase; -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.sitepark.ies.userrepository.core.domain.entity.AccessToken; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.domain.exception.UserNotFoundException; import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class CreateImpersonationToken { - private final AccessTokenRepository repository; + private final AccessTokenRepository repository; - private final AccessControl accessControl; + private final AccessControl accessControl; - private final UserRepository userRepository; + private final UserRepository userRepository; - private static Logger LOGGER = LogManager.getLogger(); + private static Logger LOGGER = LogManager.getLogger(); - @Inject - protected CreateImpersonationToken( - AccessTokenRepository repository, - AccessControl accessControl, - UserRepository userRepository) { - this.repository = repository; - this.accessControl = accessControl; - this.userRepository = userRepository; - } + @Inject + protected CreateImpersonationToken( + AccessTokenRepository repository, + AccessControl accessControl, + UserRepository userRepository) { + this.repository = repository; + this.accessControl = accessControl; + this.userRepository = userRepository; + } - public AccessToken createPersonalAccessToken(AccessToken accessToken) { + public AccessToken createPersonalAccessToken(AccessToken accessToken) { - AccessToken accessTokenToCreate = accessToken.toBuilder() - .impersonation(true) - .build(); + AccessToken accessTokenToCreate = accessToken.toBuilder().impersonation(true).build(); - if (!this.accessControl.isImpersonationTokensManageable()) { - throw new AccessDeniedException("Not allowed manage impersonation tokens"); - } + if (!this.accessControl.isImpersonationTokensManageable()) { + throw new AccessDeniedException("Not allowed manage impersonation tokens"); + } - if (this.userRepository.get(accessToken.getUser()).isEmpty()) { - throw new UserNotFoundException(accessToken.getUser()); - } + if (this.userRepository.get(accessToken.getUser()).isEmpty()) { + throw new UserNotFoundException(accessToken.getUser()); + } - if (LOGGER.isInfoEnabled()) { - LOGGER.info("create: {}", accessTokenToCreate); - } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("create: {}", accessTokenToCreate); + } - return this.repository.create(accessTokenToCreate); - } + return this.repository.create(accessTokenToCreate); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateUser.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateUser.java index 67bf73a..cc710dc 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateUser.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/CreateUser.java @@ -1,13 +1,5 @@ package com.sitepark.ies.userrepository.core.usecase; -import java.util.Arrays; -import java.util.Optional; - -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.domain.exception.AnchorAlreadyExistsException; @@ -17,81 +9,84 @@ import com.sitepark.ies.userrepository.core.port.IdGenerator; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Optional; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public final class CreateUser { - private final UserRepository repository; + private final UserRepository repository; - private final RoleAssigner roleAssigner; + private final RoleAssigner roleAssigner; - private final AccessControl accessControl; + private final AccessControl accessControl; - private final IdGenerator idGenerator; + private final IdGenerator idGenerator; - private final ExtensionsNotifier extensionsNotifier; + private final ExtensionsNotifier extensionsNotifier; - private static Logger LOGGER = LogManager.getLogger(); + private static Logger LOGGER = LogManager.getLogger(); - @Inject - protected CreateUser( - UserRepository repository, - RoleAssigner roleAssigner, - AccessControl accessControl, - IdGenerator idGenerator, - ExtensionsNotifier extensionsNotifier) { - this.repository = repository; - this.roleAssigner = roleAssigner; - this.accessControl = accessControl; - this.idGenerator = idGenerator; - this.extensionsNotifier = extensionsNotifier; - } + @Inject + protected CreateUser( + UserRepository repository, + RoleAssigner roleAssigner, + AccessControl accessControl, + IdGenerator idGenerator, + ExtensionsNotifier extensionsNotifier) { + this.repository = repository; + this.roleAssigner = roleAssigner; + this.accessControl = accessControl; + this.idGenerator = idGenerator; + this.extensionsNotifier = extensionsNotifier; + } - public String createUser(User newUser) { + public String createUser(User newUser) { - if (newUser.getId().isPresent()) { - throw new IllegalArgumentException("The ID of the user must not be set when creating."); - } + if (newUser.getId().isPresent()) { + throw new IllegalArgumentException("The ID of the user must not be set when creating."); + } - this.validateAnchor(newUser); + this.validateAnchor(newUser); - this.validateLogin(newUser); + this.validateLogin(newUser); - if (!this.accessControl.isUserCreateable()) { - throw new AccessDeniedException("Not allowed to create user " + newUser); - } + if (!this.accessControl.isUserCreateable()) { + throw new AccessDeniedException("Not allowed to create user " + newUser); + } - String generatedId = this.idGenerator.generate(); + String generatedId = this.idGenerator.generate(); - User userWithId = newUser.toBuilder().id(generatedId).build(); + User userWithId = newUser.toBuilder().id(generatedId).build(); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("create user: {}", userWithId); - } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("create user: {}", userWithId); + } - this.repository.create(userWithId); + this.repository.create(userWithId); - this.roleAssigner.assignRoleToUser( - userWithId.getRoleList(), - Arrays.asList(generatedId)); + this.roleAssigner.assignRoleToUser(userWithId.getRoleList(), Arrays.asList(generatedId)); - this.extensionsNotifier.notifyCreated(userWithId); + this.extensionsNotifier.notifyCreated(userWithId); - return userWithId.getId().get(); - } + return userWithId.getId().get(); + } - private void validateAnchor(User newUser) { - if (newUser.getAnchor().isPresent()) { - Optional anchorOwner = this.repository.resolveAnchor(newUser.getAnchor().get()); - if (anchorOwner.isPresent()) { - throw new AnchorAlreadyExistsException(newUser.getAnchor().get(), anchorOwner.get()); - } - } - } + private void validateAnchor(User newUser) { + if (newUser.getAnchor().isPresent()) { + Optional anchorOwner = this.repository.resolveAnchor(newUser.getAnchor().get()); + if (anchorOwner.isPresent()) { + throw new AnchorAlreadyExistsException(newUser.getAnchor().get(), anchorOwner.get()); + } + } + } - private void validateLogin(User newUser) { - Optional resolveLogin = this.repository.resolveLogin(newUser.getLogin()); - if (resolveLogin.isPresent()) { - throw new LoginAlreadyExistsException(newUser.getLogin(), resolveLogin.get()); - } - } + private void validateLogin(User newUser) { + Optional resolveLogin = this.repository.resolveLogin(newUser.getLogin()); + if (resolveLogin.isPresent()) { + throw new LoginAlreadyExistsException(newUser.getLogin(), resolveLogin.get()); + } + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/GetUser.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/GetUser.java index a832844..6358c16 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/GetUser.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/GetUser.java @@ -1,9 +1,5 @@ package com.sitepark.ies.userrepository.core.usecase; -import java.util.List; - -import jakarta.inject.Inject; - import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.entity.Role; import com.sitepark.ies.userrepository.core.domain.entity.User; @@ -13,43 +9,43 @@ import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import java.util.List; public final class GetUser { - private final UserRepository repository; + private final UserRepository repository; - private final IdentifierResolver identifierResolver; + private final IdentifierResolver identifierResolver; - private final RoleAssigner roleAssigner; + private final RoleAssigner roleAssigner; - private final AccessControl accessControl; + private final AccessControl accessControl; - @Inject - protected GetUser( - UserRepository repository, - IdentifierResolver identifierResolver, - RoleAssigner roleAssigner, - AccessControl accessControl) { - this.repository = repository; - this.identifierResolver = identifierResolver; - this.roleAssigner = roleAssigner; - this.accessControl = accessControl; - } + @Inject + protected GetUser( + UserRepository repository, + IdentifierResolver identifierResolver, + RoleAssigner roleAssigner, + AccessControl accessControl) { + this.repository = repository; + this.identifierResolver = identifierResolver; + this.roleAssigner = roleAssigner; + this.accessControl = accessControl; + } - public User getUser(Identifier identifier) { + public User getUser(Identifier identifier) { - String id = this.identifierResolver.resolveIdentifier(identifier); + String id = this.identifierResolver.resolveIdentifier(identifier); - if (!this.accessControl.isUserReadable(id)) { - throw new AccessDeniedException("Not allowed to reat user " + id); - } + if (!this.accessControl.isUserReadable(id)) { + throw new AccessDeniedException("Not allowed to reat user " + id); + } - User user = this.repository.get(id).orElseThrow(() -> new UserNotFoundException(id)); + User user = this.repository.get(id).orElseThrow(() -> new UserNotFoundException(id)); - List roleList = this.roleAssigner.getRolesAssignByUser(id); + List roleList = this.roleAssigner.getRolesAssignByUser(id); - return user.toBuilder() - .roleList(roleList) - .build(); - } + return user.toBuilder().roleList(roleList).build(); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/PurgeUser.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/PurgeUser.java index 0e14964..0f50ed1 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/PurgeUser.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/PurgeUser.java @@ -1,10 +1,5 @@ package com.sitepark.ies.userrepository.core.usecase; -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.domain.service.IdentifierResolver; @@ -12,52 +7,55 @@ import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.ExtensionsNotifier; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public final class PurgeUser { - private final UserRepository repository; + private final UserRepository repository; - private final IdentifierResolver identifierResolver; + private final IdentifierResolver identifierResolver; - private final AccessTokenRepository accessTokenRepository; + private final AccessTokenRepository accessTokenRepository; - private final ExtensionsNotifier extensionsNotifier; + private final ExtensionsNotifier extensionsNotifier; - private final AccessControl accessControl; + private final AccessControl accessControl; - private static Logger LOGGER = LogManager.getLogger(); + private static Logger LOGGER = LogManager.getLogger(); - @Inject - protected PurgeUser( - UserRepository repository, - IdentifierResolver identifierResolver, - ExtensionsNotifier extensionsNotifier, - AccessControl accessControl, - AccessTokenRepository accessTokenRepository) { + @Inject + protected PurgeUser( + UserRepository repository, + IdentifierResolver identifierResolver, + ExtensionsNotifier extensionsNotifier, + AccessControl accessControl, + AccessTokenRepository accessTokenRepository) { - this.repository = repository; - this.extensionsNotifier = extensionsNotifier; - this.identifierResolver = identifierResolver; - this.accessControl = accessControl; - this.accessTokenRepository = accessTokenRepository; - } + this.repository = repository; + this.extensionsNotifier = extensionsNotifier; + this.identifierResolver = identifierResolver; + this.accessControl = accessControl; + this.accessTokenRepository = accessTokenRepository; + } - public void purgeUser(Identifier identifier) { + public void purgeUser(Identifier identifier) { - String id = this.identifierResolver.resolveIdentifier(identifier); + String id = this.identifierResolver.resolveIdentifier(identifier); - if (!this.accessControl.isUserRemovable(id)) { - throw new AccessDeniedException("Not allowed to remove user " + id); - } + if (!this.accessControl.isUserRemovable(id)) { + throw new AccessDeniedException("Not allowed to remove user " + id); + } - if (LOGGER.isInfoEnabled()) { - LOGGER.info("purge user: {}", id); - } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("purge user: {}", id); + } - this.repository.remove(id); + this.repository.remove(id); - this.accessTokenRepository.purgeByUser(id); + this.accessTokenRepository.purgeByUser(id); - this.extensionsNotifier.notifyPurge(id); - } + this.extensionsNotifier.notifyPurge(id); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationToken.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationToken.java index a357149..9a38170 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationToken.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationToken.java @@ -1,40 +1,37 @@ package com.sitepark.ies.userrepository.core.usecase; -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; +import jakarta.inject.Inject; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class RevokeImpersonationToken { - private final AccessTokenRepository repository; + private final AccessTokenRepository repository; - private final AccessControl accessControl; + private final AccessControl accessControl; - private static Logger LOGGER = LogManager.getLogger(); + private static Logger LOGGER = LogManager.getLogger(); - @Inject - protected RevokeImpersonationToken( - AccessTokenRepository repository, - AccessControl accessControl) { - this.repository = repository; - this.accessControl = accessControl; - } + @Inject + protected RevokeImpersonationToken( + AccessTokenRepository repository, AccessControl accessControl) { + this.repository = repository; + this.accessControl = accessControl; + } - public void revokeImpersonationToken(String user, String id) { + public void revokeImpersonationToken(String user, String id) { - if (!this.accessControl.isImpersonationTokensManageable()) { - throw new AccessDeniedException("Not allowed manage impersonation tokens"); - } + if (!this.accessControl.isImpersonationTokensManageable()) { + throw new AccessDeniedException("Not allowed manage impersonation tokens"); + } - if (LOGGER.isInfoEnabled()) { - LOGGER.info("revoke impersonation token: {}/{}", user, id); - } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("revoke impersonation token: {}/{}", user, id); + } - this.repository.revoke(user, id); - } + this.repository.revoke(user, id); + } } diff --git a/src/main/java/com/sitepark/ies/userrepository/core/usecase/UpdateUser.java b/src/main/java/com/sitepark/ies/userrepository/core/usecase/UpdateUser.java index 36484a6..423b14f 100644 --- a/src/main/java/com/sitepark/ies/userrepository/core/usecase/UpdateUser.java +++ b/src/main/java/com/sitepark/ies/userrepository/core/usecase/UpdateUser.java @@ -1,14 +1,5 @@ package com.sitepark.ies.userrepository.core.usecase; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import com.sitepark.ies.userrepository.core.domain.entity.Role; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; @@ -19,110 +10,109 @@ import com.sitepark.ies.userrepository.core.port.ExtensionsNotifier; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public final class UpdateUser { - private final UserRepository repository; - - private final IdentifierResolver identifierResolver; + private final UserRepository repository; - private final RoleAssigner roleAssigner; + private final IdentifierResolver identifierResolver; - private final AccessControl accessControl; + private final RoleAssigner roleAssigner; - private final ExtensionsNotifier extensionsNotifier; + private final AccessControl accessControl; - private static Logger LOGGER = LogManager.getLogger(); + private final ExtensionsNotifier extensionsNotifier; - @Inject - protected UpdateUser( - UserRepository repository, - IdentifierResolver identifierResolver, - RoleAssigner roleAssigner, - AccessControl accessControl, - ExtensionsNotifier extensionsNotifier) { - this.repository = repository; - this.identifierResolver = identifierResolver; - this.roleAssigner = roleAssigner; - this.accessControl = accessControl; - this.extensionsNotifier = extensionsNotifier; - } + private static Logger LOGGER = LogManager.getLogger(); - public String updateUser(User user) { + @Inject + protected UpdateUser( + UserRepository repository, + IdentifierResolver identifierResolver, + RoleAssigner roleAssigner, + AccessControl accessControl, + ExtensionsNotifier extensionsNotifier) { + this.repository = repository; + this.identifierResolver = identifierResolver; + this.roleAssigner = roleAssigner; + this.accessControl = accessControl; + this.extensionsNotifier = extensionsNotifier; + } - User updateUser = this.buildUserWithId(user); - String id = updateUser.getId().get(); - this.validateWritable(id); - User storedUser = this.loadStoredUser(id); - this.validateLogin(updateUser); + public String updateUser(User user) { - User joinedUpdateUser = this.joinForUpdate(storedUser, updateUser); + User updateUser = this.buildUserWithId(user); + String id = updateUser.getId().get(); + this.validateWritable(id); + User storedUser = this.loadStoredUser(id); + this.validateLogin(updateUser); - if (storedUser.equals(joinedUpdateUser)) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("update(unchanged): {}", joinedUpdateUser); - } - return id; - } + User joinedUpdateUser = this.joinForUpdate(storedUser, updateUser); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("update: {}", joinedUpdateUser); - } + if (storedUser.equals(joinedUpdateUser)) { + if (LOGGER.isInfoEnabled()) { + LOGGER.info("update(unchanged): {}", joinedUpdateUser); + } + return id; + } - this.roleAssigner.reassignRoleToUser( - joinedUpdateUser.getRoleList(), - Arrays.asList(id)); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("update: {}", joinedUpdateUser); + } - this.repository.update(joinedUpdateUser); + this.roleAssigner.reassignRoleToUser(joinedUpdateUser.getRoleList(), Arrays.asList(id)); - this.extensionsNotifier.notifyUpdated(joinedUpdateUser); + this.repository.update(joinedUpdateUser); - return id; - } + this.extensionsNotifier.notifyUpdated(joinedUpdateUser); - private User buildUserWithId(User user) { + return id; + } - if (user.getIdentifier().isEmpty()) { - throw new IllegalArgumentException("For users to be updated neither an id nor an anchor is set"); - } + private User buildUserWithId(User user) { - String id = this.identifierResolver.resolveIdentifier(user.getIdentifier().get()); + if (user.getIdentifier().isEmpty()) { + throw new IllegalArgumentException( + "For users to be updated neither an id nor an anchor is set"); + } - return user.toBuilder().id(id).build(); - } + String id = this.identifierResolver.resolveIdentifier(user.getIdentifier().get()); - private void validateWritable(String id) { - if (!this.accessControl.isUserWritable(id)) { - throw new AccessDeniedException("Not allowed to update user " + id); - } - } + return user.toBuilder().id(id).build(); + } - private User loadStoredUser(String id) { - User storedUser = this.repository.get(id) - .orElseThrow(() -> new UserNotFoundException(id)); + private void validateWritable(String id) { + if (!this.accessControl.isUserWritable(id)) { + throw new AccessDeniedException("Not allowed to update user " + id); + } + } - List roleList = this.roleAssigner.getRolesAssignByUser(storedUser.getId().get()); - return storedUser.toBuilder() - .roleList(roleList) - .build(); - } + private User loadStoredUser(String id) { + User storedUser = this.repository.get(id).orElseThrow(() -> new UserNotFoundException(id)); - private void validateLogin(User user) { - Optional resolveLogin = this.repository.resolveLogin(user.getLogin()); - if (resolveLogin.isPresent() && !resolveLogin.equals(user.getId())) { - throw new LoginAlreadyExistsException(user.getLogin(), resolveLogin.get()); - } - } + List roleList = this.roleAssigner.getRolesAssignByUser(storedUser.getId().get()); + return storedUser.toBuilder().roleList(roleList).build(); + } - private User joinForUpdate(User storedUser, User updateUser) { + private void validateLogin(User user) { + Optional resolveLogin = this.repository.resolveLogin(user.getLogin()); + if (resolveLogin.isPresent() && !resolveLogin.equals(user.getId())) { + throw new LoginAlreadyExistsException(user.getLogin(), resolveLogin.get()); + } + } - if (updateUser.getAnchor().isEmpty() && storedUser.getAnchor().isPresent()) { - return updateUser.toBuilder() - .anchor(storedUser.getAnchor().get()) - .build(); - } + private User joinForUpdate(User storedUser, User updateUser) { - return updateUser; + if (updateUser.getAnchor().isEmpty() && storedUser.getAnchor().isPresent()) { + return updateUser.toBuilder().anchor(storedUser.getAnchor().get()).build(); + } - } + return updateUser; + } } diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index d18c1da..17d04c0 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -3,23 +3,23 @@ * and data structures, of the user repository. */ module com.sitepark.ies.userrepository.core { - exports com.sitepark.ies.userrepository.core.domain.entity; - exports com.sitepark.ies.userrepository.core.domain.entity.identity; - exports com.sitepark.ies.userrepository.core.domain.entity.role; - exports com.sitepark.ies.userrepository.core.domain.exception; - exports com.sitepark.ies.userrepository.core.port; - exports com.sitepark.ies.userrepository.core.usecase; - requires org.apache.logging.log4j; - requires com.github.spotbugs.annotations; - requires jakarta.inject; - requires transitive com.fasterxml.jackson.databind; - requires com.fasterxml.jackson.annotation; - requires com.fasterxml.jackson.datatype.jdk8; - requires com.fasterxml.jackson.datatype.jsr310; - requires org.eclipse.jdt.annotation; + exports com.sitepark.ies.userrepository.core.domain.entity; + exports com.sitepark.ies.userrepository.core.domain.entity.identity; + exports com.sitepark.ies.userrepository.core.domain.entity.role; + exports com.sitepark.ies.userrepository.core.domain.exception; + exports com.sitepark.ies.userrepository.core.port; + exports com.sitepark.ies.userrepository.core.usecase; - opens com.sitepark.ies.userrepository.core.domain.entity; - opens com.sitepark.ies.userrepository.core.domain.entity.role; - opens com.sitepark.ies.userrepository.core.domain.entity.identity; + requires org.apache.logging.log4j; + requires com.github.spotbugs.annotations; + requires jakarta.inject; + requires transitive com.fasterxml.jackson.databind; + requires com.fasterxml.jackson.annotation; + requires com.fasterxml.jackson.datatype.jdk8; + requires com.fasterxml.jackson.datatype.jsr310; + requires org.eclipse.jdt.annotation; -} \ No newline at end of file + opens com.sitepark.ies.userrepository.core.domain.entity; + opens com.sitepark.ies.userrepository.core.domain.entity.role; + opens com.sitepark.ies.userrepository.core.domain.entity.identity; +} diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AccessTokenTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AccessTokenTest.java index f22746a..5553d71 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AccessTokenTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AccessTokenTest.java @@ -5,494 +5,497 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.TooManyMethods", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL", - "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL", + "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" }) class AccessTokenTest { - private static final ZoneId ZONE_ID = ZoneId.of( "Europe/Berlin" ); - - private static final String TOKEN_NAME = "Test Token"; - - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(AccessToken.class) - .verify(); - } - - @Test - void testSetUser() throws JsonProcessingException { - AccessToken accessToken = AccessToken.builder() - .user("345") - .name(TOKEN_NAME) - .build(); - assertEquals("345", accessToken.getUser(), "wrong user"); - } - - @Test - void testSetUserWithNull() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().user(null); - }); - } - - @Test - void testSetUserWithZero() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().user("0"); - }); - } - - @Test - void testSetUserWithInvalidValue() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().user("1x"); - }); - } - - @Test - void testSetName() throws JsonProcessingException { - AccessToken accessToken = AccessToken.builder() - .user("345") - .name(TOKEN_NAME) - .build(); - assertEquals(TOKEN_NAME, accessToken.getName(), "wrong name"); - } - - @Test - void testSetNullName() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().name(null); - }); - } - - @Test - void testSetBlankName() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().name(" "); - }); - } - - @Test - void testBuildUserNotSet() throws JsonProcessingException { - assertThrows(IllegalStateException.class, () -> { - AccessToken.builder() - .name(TOKEN_NAME) - .build(); - }); - } - - @Test - void testBuildNameNotSet() throws JsonProcessingException { - assertThrows(IllegalStateException.class, () -> { - AccessToken.builder() - .user("123") - .build(); - }); - } - - @Test - void testSetId() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .id("123") - .build(); - assertEquals("123", accessToken.getId().get(), "wrong id"); - } - - @Test - void testGetEmptyId() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .build(); - assertTrue(accessToken.getId().isEmpty(), "id should be empty"); - } - - @Test - void testSetIdWithNull() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().id(null); - }); - } - - @Test - void testSetIdWithZero() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().id("0"); - }); - } - - @Test - void testSetIdWithInvalidValue() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().id("1x"); - }); - } - - @Test - void testSetToken() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .token("abc") - .build(); - assertEquals("abc", accessToken.getToken().get(), "wrong token"); - } - - @Test - void testSetNullToken() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().token(null); - }); - } - - @Test - void testSetBlankToken() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().token(" "); - }); - } - - @Test - void testSetCreatedAt() throws JsonProcessingException { - - OffsetDateTime createdAt = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - AccessToken accessToken = this.createBuilderWithRequiredValues() - .createdAt(createdAt) - .build(); - - assertEquals(createdAt, accessToken.getCreatedAt().get(), "unexpected createAt"); - } - - @Test - void testSetNullCreatedAt() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().createdAt(null); - }); - } - - @Test - void testSetExpiresAt() throws JsonProcessingException { - - OffsetDateTime expiresAt = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - AccessToken accessToken = this.createBuilderWithRequiredValues() - .expiresAt(expiresAt) - .build(); - - assertEquals(expiresAt, accessToken.getExpiresAt().get(), "unexpected expiresAt"); - } - - @Test - void testSetNullExpiresAt() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().expiresAt(null); - }); - } - - @Test - void testSetLastUsed() throws JsonProcessingException { - - OffsetDateTime lastUsed = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - AccessToken accessToken = this.createBuilderWithRequiredValues() - .lastUsed(lastUsed) - .build(); - - assertEquals(lastUsed, accessToken.getLastUsed().get(), "unexpected lastUsed"); - } - - @Test - void testSetNullLastUsed() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().lastUsed(null); - }); - } - - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void testSetScopeListViaList() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .scopeList(Arrays.asList("a", "b")) - .build(); - - assertEquals(Arrays.asList("a", "b"), accessToken.getScopeList(), "unexpected scopeList"); - } - - @Test - void testSetNullScopeListViaList() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().scopeList((List)null); - }); - } - - @Test - void testSetNullScopeViaList() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().scopeList(Arrays.asList("a", null)); - }); - } - - @Test - void testSetBlankScopeListViaList() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().scopeList(Arrays.asList("a", " ")); - }); - } - - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void testOverwriteScopeListViaList() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .scopeList(Arrays.asList("a", "b")) - .build(); - - AccessToken overwritten = accessToken.toBuilder() - .scopeList(Arrays.asList("c", "d")) - .build(); - - assertEquals(Arrays.asList("c", "d"), overwritten.getScopeList(), "unexpected scopeList"); - } - - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void testSetScopeListViaVArgs() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .scopeList("a", "b") - .build(); - - assertEquals(Arrays.asList("a", "b"), accessToken.getScopeList(), "unexpected scopeList"); - } - - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void testOverwriteScopeListViaVArgs() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .scopeList("a", "b") - .build(); - AccessToken overwritten = accessToken.toBuilder() - .scopeList("c", "d") - .build(); - - assertEquals(Arrays.asList("c", "d"), overwritten.getScopeList(), "unexpected scopeList"); - } - - @Test - void testSetNullScopeListViaVArgs() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().scopeList((String[])null); - }); - } - - @Test - void testSetNullScopeViaVArgs() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - AccessToken.builder().scopeList("a", null); - }); - } - - @Test - void testSetBlankScopeViaVArgs() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().scopeList("a", " "); - }); - } - - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void testAddScope() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .scopeList("a", "b") - .build(); - - AccessToken addition = accessToken.toBuilder() - .scope("c") - .build(); - - assertEquals(Arrays.asList("a", "b", "c"), addition.getScopeList(), "unexpected scopes"); - } - - @Test - void testAddNullScope() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - this.createBuilderWithRequiredValues() - .scope(null); - }); - } - - @Test - void testAddBlankScope() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - AccessToken.builder().scope(" "); - }); - } - - @Test - void testSetImpersonationTrue() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .impersonation(true) - .build(); - assertTrue(accessToken.isImpersonation(), "unexpected impersonation"); - } - - @Test - void testSetImpersonationFalse() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .impersonation(false) - .build(); - assertFalse(accessToken.isImpersonation(), "unexpected impersonation"); - } - - @Test - void testSetActiveTrue() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .active(true) - .build(); - assertTrue(accessToken.isActive(), "unexpected active"); - } - - @Test - void testSetActiveFalse() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .active(false) - .build(); - assertFalse(accessToken.isActive(), "unexpected active"); - } - - @Test - void testSetRevokedTrue() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .revoked(true) - .build(); - assertTrue(accessToken.isRevoked(), "unexpected revoked"); - } - - @Test - void testSetRevokedFalse() throws JsonProcessingException { - AccessToken accessToken = this.createBuilderWithRequiredValues() - .revoked(false) - .build(); - assertFalse(accessToken.isRevoked(), "unexpected revoked"); - } - - @Test - void testSerialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - - OffsetDateTime createdAt = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime expiredAt = LocalDate.of(2023, 12, 12).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime lastUpdate = LocalDate.of(2023, 8, 25).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - AccessToken accessToken = AccessToken.builder() - .id("123") - .user("345") - .name(TOKEN_NAME) - .createdAt(createdAt) - .expiresAt(expiredAt) - .lastUsed(lastUpdate) - .impersonation(true) - .build(); - - String json = mapper.writeValueAsString(accessToken); - - String expected = "{" + - "\"id\":\"123\"," + - "\"user\":\"345\"," + - "\"name\":\"Test Token\"," + - "\"createdAt\":\"2023-08-21T00:00:00+02:00\"," + - "\"expiresAt\":\"2023-12-12T00:00:00+01:00\"," + - "\"lastUsed\":\"2023-08-25T00:00:00+02:00\"," + - "\"impersonation\":true," + - "\"active\":true," + - "\"revoked\":false" + - "}"; - - assertEquals(expected, json, "unexpected json"); - } - - @Test - void testDeserialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - String json = "{" + - "\"id\":123," + - "\"user\":345," + - "\"name\":\"Test Token\"," + - "\"createdAt\":\"2023-08-21T00:00:00+02:00\"," + - "\"expiresAt\":\"2023-12-12T00:00:00+01:00\"," + - "\"lastUsed\":\"2023-08-25T00:00:00+02:00\"," + - "\"impersonation\":true," + - "\"active\":true," + - "\"revoked\":false" + - "}"; - - AccessToken accessToken = mapper.readValue(json, AccessToken.class); - - OffsetDateTime createdAt = LocalDate.of(2023, 8, 21) - .atStartOfDay() - .atZone(ZONE_ID) - .toOffsetDateTime() - .withOffsetSameInstant(ZoneOffset.UTC); - OffsetDateTime expiredAt = LocalDate.of(2023, 12, 12) - .atStartOfDay() - .atZone(ZONE_ID) - .toOffsetDateTime() - .withOffsetSameInstant(ZoneOffset.UTC); - OffsetDateTime lastUpdate = LocalDate.of(2023, 8, 25) - .atStartOfDay() - .atZone(ZONE_ID) - .toOffsetDateTime() - .withOffsetSameInstant(ZoneOffset.UTC); - - AccessToken expected = AccessToken.builder() - .id("123") - .user("345") - .name(TOKEN_NAME) - .createdAt(createdAt) - .expiresAt(expiredAt) - .lastUsed(lastUpdate) - .impersonation(true) - .build(); - - assertEquals(expected, accessToken, "unexpected accessToken"); - } - - private AccessToken.Builder createBuilderWithRequiredValues() { - return AccessToken.builder() - .user("345") - .name(TOKEN_NAME); - } - + private static final ZoneId ZONE_ID = ZoneId.of("Europe/Berlin"); + + private static final String TOKEN_NAME = "Test Token"; + + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(AccessToken.class).verify(); + } + + @Test + void testSetUser() throws JsonProcessingException { + AccessToken accessToken = AccessToken.builder().user("345").name(TOKEN_NAME).build(); + assertEquals("345", accessToken.getUser(), "wrong user"); + } + + @Test + void testSetUserWithNull() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().user(null); + }); + } + + @Test + void testSetUserWithZero() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().user("0"); + }); + } + + @Test + void testSetUserWithInvalidValue() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().user("1x"); + }); + } + + @Test + void testSetName() throws JsonProcessingException { + AccessToken accessToken = AccessToken.builder().user("345").name(TOKEN_NAME).build(); + assertEquals(TOKEN_NAME, accessToken.getName(), "wrong name"); + } + + @Test + void testSetNullName() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().name(null); + }); + } + + @Test + void testSetBlankName() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().name(" "); + }); + } + + @Test + void testBuildUserNotSet() throws JsonProcessingException { + assertThrows( + IllegalStateException.class, + () -> { + AccessToken.builder().name(TOKEN_NAME).build(); + }); + } + + @Test + void testBuildNameNotSet() throws JsonProcessingException { + assertThrows( + IllegalStateException.class, + () -> { + AccessToken.builder().user("123").build(); + }); + } + + @Test + void testSetId() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().id("123").build(); + assertEquals("123", accessToken.getId().get(), "wrong id"); + } + + @Test + void testGetEmptyId() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().build(); + assertTrue(accessToken.getId().isEmpty(), "id should be empty"); + } + + @Test + void testSetIdWithNull() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().id(null); + }); + } + + @Test + void testSetIdWithZero() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().id("0"); + }); + } + + @Test + void testSetIdWithInvalidValue() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().id("1x"); + }); + } + + @Test + void testSetToken() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().token("abc").build(); + assertEquals("abc", accessToken.getToken().get(), "wrong token"); + } + + @Test + void testSetNullToken() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().token(null); + }); + } + + @Test + void testSetBlankToken() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().token(" "); + }); + } + + @Test + void testSetCreatedAt() throws JsonProcessingException { + + OffsetDateTime createdAt = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + + AccessToken accessToken = this.createBuilderWithRequiredValues().createdAt(createdAt).build(); + + assertEquals(createdAt, accessToken.getCreatedAt().get(), "unexpected createAt"); + } + + @Test + void testSetNullCreatedAt() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().createdAt(null); + }); + } + + @Test + void testSetExpiresAt() throws JsonProcessingException { + + OffsetDateTime expiresAt = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + + AccessToken accessToken = this.createBuilderWithRequiredValues().expiresAt(expiresAt).build(); + + assertEquals(expiresAt, accessToken.getExpiresAt().get(), "unexpected expiresAt"); + } + + @Test + void testSetNullExpiresAt() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().expiresAt(null); + }); + } + + @Test + void testSetLastUsed() throws JsonProcessingException { + + OffsetDateTime lastUsed = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + + AccessToken accessToken = this.createBuilderWithRequiredValues().lastUsed(lastUsed).build(); + + assertEquals(lastUsed, accessToken.getLastUsed().get(), "unexpected lastUsed"); + } + + @Test + void testSetNullLastUsed() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().lastUsed(null); + }); + } + + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void testSetScopeListViaList() throws JsonProcessingException { + AccessToken accessToken = + this.createBuilderWithRequiredValues().scopeList(Arrays.asList("a", "b")).build(); + + assertEquals(Arrays.asList("a", "b"), accessToken.getScopeList(), "unexpected scopeList"); + } + + @Test + void testSetNullScopeListViaList() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().scopeList((List) null); + }); + } + + @Test + void testSetNullScopeViaList() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().scopeList(Arrays.asList("a", null)); + }); + } + + @Test + void testSetBlankScopeListViaList() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().scopeList(Arrays.asList("a", " ")); + }); + } + + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void testOverwriteScopeListViaList() throws JsonProcessingException { + AccessToken accessToken = + this.createBuilderWithRequiredValues().scopeList(Arrays.asList("a", "b")).build(); + + AccessToken overwritten = accessToken.toBuilder().scopeList(Arrays.asList("c", "d")).build(); + + assertEquals(Arrays.asList("c", "d"), overwritten.getScopeList(), "unexpected scopeList"); + } + + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void testSetScopeListViaVArgs() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().scopeList("a", "b").build(); + + assertEquals(Arrays.asList("a", "b"), accessToken.getScopeList(), "unexpected scopeList"); + } + + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void testOverwriteScopeListViaVArgs() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().scopeList("a", "b").build(); + AccessToken overwritten = accessToken.toBuilder().scopeList("c", "d").build(); + + assertEquals(Arrays.asList("c", "d"), overwritten.getScopeList(), "unexpected scopeList"); + } + + @Test + void testSetNullScopeListViaVArgs() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().scopeList((String[]) null); + }); + } + + @Test + void testSetNullScopeViaVArgs() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + AccessToken.builder().scopeList("a", null); + }); + } + + @Test + void testSetBlankScopeViaVArgs() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().scopeList("a", " "); + }); + } + + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void testAddScope() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().scopeList("a", "b").build(); + + AccessToken addition = accessToken.toBuilder().scope("c").build(); + + assertEquals(Arrays.asList("a", "b", "c"), addition.getScopeList(), "unexpected scopes"); + } + + @Test + void testAddNullScope() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + this.createBuilderWithRequiredValues().scope(null); + }); + } + + @Test + void testAddBlankScope() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + AccessToken.builder().scope(" "); + }); + } + + @Test + void testSetImpersonationTrue() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().impersonation(true).build(); + assertTrue(accessToken.isImpersonation(), "unexpected impersonation"); + } + + @Test + void testSetImpersonationFalse() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().impersonation(false).build(); + assertFalse(accessToken.isImpersonation(), "unexpected impersonation"); + } + + @Test + void testSetActiveTrue() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().active(true).build(); + assertTrue(accessToken.isActive(), "unexpected active"); + } + + @Test + void testSetActiveFalse() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().active(false).build(); + assertFalse(accessToken.isActive(), "unexpected active"); + } + + @Test + void testSetRevokedTrue() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().revoked(true).build(); + assertTrue(accessToken.isRevoked(), "unexpected revoked"); + } + + @Test + void testSetRevokedFalse() throws JsonProcessingException { + AccessToken accessToken = this.createBuilderWithRequiredValues().revoked(false).build(); + assertFalse(accessToken.isRevoked(), "unexpected revoked"); + } + + @Test + void testSerialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + + OffsetDateTime createdAt = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime expiredAt = + LocalDate.of(2023, 12, 12).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime lastUpdate = + LocalDate.of(2023, 8, 25).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + + AccessToken accessToken = + AccessToken.builder() + .id("123") + .user("345") + .name(TOKEN_NAME) + .createdAt(createdAt) + .expiresAt(expiredAt) + .lastUsed(lastUpdate) + .impersonation(true) + .build(); + + String json = mapper.writeValueAsString(accessToken); + + String expected = + """ + {\ + "id":"123",\ + "user":"345",\ + "name":"Test Token",\ + "createdAt":"2023-08-21T00:00:00+02:00",\ + "expiresAt":"2023-12-12T00:00:00+01:00",\ + "lastUsed":"2023-08-25T00:00:00+02:00",\ + "impersonation":true,\ + "active":true,\ + "revoked":false\ + }"""; + + assertEquals(expected, json, "unexpected json"); + } + + @Test + void testDeserialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + String json = + """ + {\ + "id":123,\ + "user":345,\ + "name":"Test Token",\ + "createdAt":"2023-08-21T00:00:00+02:00",\ + "expiresAt":"2023-12-12T00:00:00+01:00",\ + "lastUsed":"2023-08-25T00:00:00+02:00",\ + "impersonation":true,\ + "active":true,\ + "revoked":false\ + }"""; + + AccessToken accessToken = mapper.readValue(json, AccessToken.class); + + OffsetDateTime createdAt = + LocalDate.of(2023, 8, 21) + .atStartOfDay() + .atZone(ZONE_ID) + .toOffsetDateTime() + .withOffsetSameInstant(ZoneOffset.UTC); + OffsetDateTime expiredAt = + LocalDate.of(2023, 12, 12) + .atStartOfDay() + .atZone(ZONE_ID) + .toOffsetDateTime() + .withOffsetSameInstant(ZoneOffset.UTC); + OffsetDateTime lastUpdate = + LocalDate.of(2023, 8, 25) + .atStartOfDay() + .atZone(ZONE_ID) + .toOffsetDateTime() + .withOffsetSameInstant(ZoneOffset.UTC); + + AccessToken expected = + AccessToken.builder() + .id("123") + .user("345") + .name(TOKEN_NAME) + .createdAt(createdAt) + .expiresAt(expiredAt) + .lastUsed(lastUpdate) + .impersonation(true) + .build(); + + assertEquals(expected, accessToken, "unexpected accessToken"); + } + + private AccessToken.Builder createBuilderWithRequiredValues() { + return AccessToken.builder().user("345").name(TOKEN_NAME); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AnchorTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AnchorTest.java index d626f86..4375a38 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AnchorTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/AnchorTest.java @@ -6,96 +6,102 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sitepark.ies.userrepository.core.domain.exception.InvalidAnchorException; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class AnchorTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(Anchor.class) - .verify(); - } - - @Test - void testOfNullString() { - Anchor anchor = Anchor.ofString(null); - assertNull(anchor, "anchor should be null"); - } - - @Test - void testOfBlankString() { - Anchor anchor = Anchor.ofString(" "); - assertEquals(Anchor.EMPTY, anchor, "anchor should be Anchor.EMPTY"); - } - - @Test - void testValidateValidAnchor() { - assertDoesNotThrow(() -> { - Anchor.ofString("123a"); - }); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testValidateOnlyDigits() { - InvalidAnchorException e = assertThrows(InvalidAnchorException.class, () -> { - Anchor.ofString("1234556789012345"); - }, "anchor must not only contain numbers"); - assertEquals("1234556789012345", e.getName(), "unexpected name"); - assertNotNull(e.getMessage(), "message is null"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testValidateInvalidChars() { - InvalidAnchorException e = assertThrows(InvalidAnchorException.class, () -> { - Anchor.ofString("a.b,c"); - }, "anchor must not contain commas"); - assertEquals("a.b,c", e.getName(), "unexpected name"); - assertNotNull(e.getMessage(), "message is null"); - } - - @Test - void testToString() { - Anchor anchor = Anchor.ofString("a.b.c"); - assertEquals("a.b.c", anchor.toString(), "unexpected string representation"); - } - - @Test - void testEmptyAnchorToString() { - Anchor anchor = Anchor.EMPTY; - assertEquals("EMPTY", anchor.toString(), "unexpected string representation"); - } - - @Test - void testSerialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - - Anchor anchor = Anchor.ofString("abc"); - - String json = mapper.writeValueAsString(anchor); - - assertEquals("\"abc\"", json, "unexpected value"); - } - - @Test - void testDeserialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - - String json = "\"abc\""; - - Anchor anchor = mapper.readValue(json, Anchor.class); - - assertEquals("abc", anchor.getName(), "unexpected anchor"); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(Anchor.class).verify(); + } + + @Test + void testOfNullString() { + Anchor anchor = Anchor.ofString(null); + assertNull(anchor, "anchor should be null"); + } + + @Test + void testOfBlankString() { + Anchor anchor = Anchor.ofString(" "); + assertEquals(Anchor.EMPTY, anchor, "anchor should be Anchor.EMPTY"); + } + + @Test + void testValidateValidAnchor() { + assertDoesNotThrow( + () -> { + Anchor.ofString("123a"); + }); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testValidateOnlyDigits() { + InvalidAnchorException e = + assertThrows( + InvalidAnchorException.class, + () -> { + Anchor.ofString("1234556789012345"); + }, + "anchor must not only contain numbers"); + assertEquals("1234556789012345", e.getName(), "unexpected name"); + assertNotNull(e.getMessage(), "message is null"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testValidateInvalidChars() { + InvalidAnchorException e = + assertThrows( + InvalidAnchorException.class, + () -> { + Anchor.ofString("a.b,c"); + }, + "anchor must not contain commas"); + assertEquals("a.b,c", e.getName(), "unexpected name"); + assertNotNull(e.getMessage(), "message is null"); + } + + @Test + void testToString() { + Anchor anchor = Anchor.ofString("a.b.c"); + assertEquals("a.b.c", anchor.toString(), "unexpected string representation"); + } + + @Test + void testEmptyAnchorToString() { + Anchor anchor = Anchor.EMPTY; + assertEquals("EMPTY", anchor.toString(), "unexpected string representation"); + } + + @Test + void testSerialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + + Anchor anchor = Anchor.ofString("abc"); + + String json = mapper.writeValueAsString(anchor); + + assertEquals("\"abc\"", json, "unexpected value"); + } + + @Test + void testDeserialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + + String json = "\"abc\""; + + Anchor anchor = mapper.readValue(json, Anchor.class); + + assertEquals("abc", anchor.getName(), "unexpected anchor"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/IdentifierTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/IdentifierTest.java index 44900a7..a35386a 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/IdentifierTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/IdentifierTest.java @@ -3,114 +3,118 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL" }) class IdentifierTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(Identifier.class) - .verify(); - } - - @Test - void testToStringWithId() { - Identifier identifier = Identifier.ofString("123"); - assertEquals("123", identifier.toString(), "unexpecated identifier"); - } - - @Test - void testToStringWithAnchor() { - Identifier identifier = Identifier.ofString("abc"); - assertEquals("abc", identifier.toString(), "unexpecated identifier"); - } - - @Test - void testOfStringToId() { - Identifier identifier = Identifier.ofString("123"); - assertEquals(Optional.of("123"), identifier.getId(), "id exprected"); - } - - @Test - void testOfStringToAnchor() { - Identifier identifier = Identifier.ofString("abc"); - Anchor anchor = Anchor.ofString("abc"); - assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); - } - - @Test - void testOfStringWithLongString() { - Identifier identifier = Identifier.ofString("abcdefghijklmnopqrstuvwxyz"); - Anchor anchor = Anchor.ofString("abcdefghijklmnopqrstuvwxyz"); - assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); - } - - @Test - void testOfStringWithDot() { - Identifier identifier = Identifier.ofString("123.b"); - Anchor anchor = Anchor.ofString("123.b"); - assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); - } - - @Test - void testOfStringWithNull() { - assertThrows(NullPointerException.class, () -> { - Identifier.ofString(null); - }); - } - - @Test - void testOfStringWithBlank() { - assertThrows(IllegalArgumentException.class, () -> { - Identifier.ofString(" "); - }); - } - - @Test - void testOfId() { - Identifier identifier = Identifier.ofId("123"); - assertEquals(Optional.of("123"), identifier.getId(), "id exprected"); - } - - @Test - void testOfIdWithZero() { - assertThrows(IllegalArgumentException.class, () -> { - Identifier.ofId("0"); - }); - } - - @Test - void testOfIdWithInvalidId() { - assertThrows(IllegalArgumentException.class, () -> { - Identifier.ofId("0x"); - }); - } - - @Test - void testOfAnchor() { - Anchor anchor = Anchor.ofString("abc"); - Identifier identifier = Identifier.ofAnchor(anchor); - assertEquals( - Optional.of(Anchor.ofString("abc")), - identifier.getAnchor(), - "anchor exprected"); - } - - @Test - void testOfAnchorWithNull() { - assertThrows(NullPointerException.class, () -> { - Identifier.ofAnchor(null); - }); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(Identifier.class).verify(); + } + + @Test + void testToStringWithId() { + Identifier identifier = Identifier.ofString("123"); + assertEquals("123", identifier.toString(), "unexpecated identifier"); + } + + @Test + void testToStringWithAnchor() { + Identifier identifier = Identifier.ofString("abc"); + assertEquals("abc", identifier.toString(), "unexpecated identifier"); + } + + @Test + void testOfStringToId() { + Identifier identifier = Identifier.ofString("123"); + assertEquals(Optional.of("123"), identifier.getId(), "id exprected"); + } + + @Test + void testOfStringToAnchor() { + Identifier identifier = Identifier.ofString("abc"); + Anchor anchor = Anchor.ofString("abc"); + assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); + } + + @Test + void testOfStringWithLongString() { + Identifier identifier = Identifier.ofString("abcdefghijklmnopqrstuvwxyz"); + Anchor anchor = Anchor.ofString("abcdefghijklmnopqrstuvwxyz"); + assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); + } + + @Test + void testOfStringWithDot() { + Identifier identifier = Identifier.ofString("123.b"); + Anchor anchor = Anchor.ofString("123.b"); + assertEquals(Optional.of(anchor), identifier.getAnchor(), "anchor exprected"); + } + + @Test + void testOfStringWithNull() { + assertThrows( + NullPointerException.class, + () -> { + Identifier.ofString(null); + }); + } + + @Test + void testOfStringWithBlank() { + assertThrows( + IllegalArgumentException.class, + () -> { + Identifier.ofString(" "); + }); + } + + @Test + void testOfId() { + Identifier identifier = Identifier.ofId("123"); + assertEquals(Optional.of("123"), identifier.getId(), "id exprected"); + } + + @Test + void testOfIdWithZero() { + assertThrows( + IllegalArgumentException.class, + () -> { + Identifier.ofId("0"); + }); + } + + @Test + void testOfIdWithInvalidId() { + assertThrows( + IllegalArgumentException.class, + () -> { + Identifier.ofId("0x"); + }); + } + + @Test + void testOfAnchor() { + Anchor anchor = Anchor.ofString("abc"); + Identifier identifier = Identifier.ofAnchor(anchor); + assertEquals(Optional.of(Anchor.ofString("abc")), identifier.getAnchor(), "anchor exprected"); + } + + @Test + void testOfAnchorWithNull() { + assertThrows( + NullPointerException.class, + () -> { + Identifier.ofAnchor(null); + }); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/RoleTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/RoleTest.java index 8acf465..50dff03 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/RoleTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/RoleTest.java @@ -3,78 +3,78 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL" }) class RoleTest { - private static final String TEST_ROLE_NAME = "ADMINISTRATOR"; - - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(Role.class) - .verify(); - } + private static final String TEST_ROLE_NAME = "ADMINISTRATOR"; - @Test - void testOfName() { - Role role = Role.ofName(TEST_ROLE_NAME); - assertEquals(TEST_ROLE_NAME, role.getName(), "unexprected name"); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(Role.class).verify(); + } - @Test - @SuppressFBWarnings("NP_NULL_PARAM_DEREF_NONVIRTUAL") - void testOfNameWithNull() { - assertThrows(NullPointerException.class, () -> { - Role.ofName(null); - }); - } + @Test + void testOfName() { + Role role = Role.ofName(TEST_ROLE_NAME); + assertEquals(TEST_ROLE_NAME, role.getName(), "unexprected name"); + } - @Test - void testOfNameWithBlank() { - assertThrows(IllegalArgumentException.class, () -> { - Role.ofName(" "); - }); - } + @Test + @SuppressFBWarnings("NP_NULL_PARAM_DEREF_NONVIRTUAL") + void testOfNameWithNull() { + assertThrows( + NullPointerException.class, + () -> { + Role.ofName(null); + }); + } - @Test - void testToString() { - Role role = Role.ofName(TEST_ROLE_NAME); - assertEquals(TEST_ROLE_NAME, role.toString(), "unexprected string representation"); - } + @Test + void testOfNameWithBlank() { + assertThrows( + IllegalArgumentException.class, + () -> { + Role.ofName(" "); + }); + } - @Test - void testSerialize() throws JsonProcessingException { + @Test + void testToString() { + Role role = Role.ofName(TEST_ROLE_NAME); + assertEquals(TEST_ROLE_NAME, role.toString(), "unexprected string representation"); + } - ObjectMapper mapper = new ObjectMapper(); + @Test + void testSerialize() throws JsonProcessingException { - Role role = Role.ofName(TEST_ROLE_NAME); + ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(role); + Role role = Role.ofName(TEST_ROLE_NAME); - assertEquals("\"" + TEST_ROLE_NAME + "\"", json, "unexpected value"); - } + String json = mapper.writeValueAsString(role); - @Test - void testDeserialize() throws JsonProcessingException { + assertEquals("\"" + TEST_ROLE_NAME + "\"", json, "unexpected value"); + } - ObjectMapper mapper = new ObjectMapper(); + @Test + void testDeserialize() throws JsonProcessingException { - String json = "\"" + TEST_ROLE_NAME + "\""; + ObjectMapper mapper = new ObjectMapper(); - Role role = mapper.readValue(json, Role.class); + String json = "\"" + TEST_ROLE_NAME + "\""; - assertEquals(TEST_ROLE_NAME, role.getName(), "unexpected anchor"); - } + Role role = mapper.readValue(json, Role.class); + assertEquals(TEST_ROLE_NAME, role.getName(), "unexpected anchor"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserTest.java index bb9aa93..548b800 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserTest.java @@ -5,12 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -19,665 +13,605 @@ import com.sitepark.ies.userrepository.core.domain.entity.identity.LdapIdentity; import com.sitepark.ies.userrepository.core.domain.entity.role.Ref; import com.sitepark.ies.userrepository.core.domain.entity.role.UserLevelRoles; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.AvoidDuplicateLiterals", - "PMD.TooManyMethods", - "PMD.GodClass" -}) +@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods", "PMD.GodClass"}) @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL", - "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL", + "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" }) class UserTest { - private static Identity TEST_IDENTITY = LdapIdentity.builder() - .server(2) - .dn("userdn") - .build(); - - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(User.class) - .verify(); - } - - @Test - void testBuildWithoutLogin() { - assertThrows(IllegalStateException.class, () -> { - User.builder().build(); - }); - } - - @Test - void testSetLogin() { - User user = User.builder() - .login("peterpan") - .build(); - assertEquals("peterpan", user.getLogin(), "unexpected login"); - } - - @Test - void testSetIdentifierWithId() { - Identifier id = Identifier.ofId("123"); - User user = this.createBuilderWithRequiredValues() - .identifier(id) - .build(); - assertEquals("123", user.getId().get(), "unexpected id"); - } - - @Test - void testSetIdentifierWithAnchor() { - Identifier anchor = Identifier.ofAnchor(Anchor.ofString("abc")); - User user = this.createBuilderWithRequiredValues() - .identifier(anchor) - .build(); - assertEquals("abc", user.getAnchor().get().getName(), "unexpected anchor"); - } - - @Test - void testSetId() { - User user = this.createBuilderWithRequiredValues() - .id("123") - .build(); - assertEquals("123", user.getId().get(), "unexpected id"); - } - - @Test - void testGetEmptyId() { - User user = this.createBuilderWithRequiredValues() - .build(); - assertTrue(user.getId().isEmpty(), "id should be empty"); - } - - @Test - void testGetIdentifierWithId() { - User user = this.createBuilderWithRequiredValues() - .id("123") - .build(); - assertEquals( - Identifier.ofId("123"), - user.getIdentifier().get(), - "unexpected identifier"); - } - - @Test - void testGetIdentifierWithAnchor() { - User user = this.createBuilderWithRequiredValues() - .anchor("abc") - .build(); - assertEquals( - Identifier.ofAnchor(Anchor.ofString("abc")), - user.getIdentifier().get(), - "unexpected identifier"); - } - - @Test - void testGetEmptyIdentifier() { - User user = this.createBuilderWithRequiredValues() - .build(); - assertTrue( - user.getIdentifier().isEmpty(), - "identifier should be empty"); - } - - @Test - void testSetIdWithZero() { - assertThrows(IllegalArgumentException.class, () -> { - User.builder().id("0"); - }, "id 0 should't be allowed"); - } - - @Test - void testSetIdWithNull() { - assertThrows(NullPointerException.class, () -> { - User.builder().id(null); - }, "null should't be allowed"); - } - - @Test - void testSeIdWithInvalidValue() { - assertThrows(IllegalArgumentException.class, () -> { - User.builder().id("0x"); - }, "invalid id should't be allowed"); - } - - @Test - void testSetAnchor() { - Anchor anchor = Anchor.ofString("user.pan.peter"); - User user = this.createBuilderWithRequiredValues() - .anchor(anchor) - .build(); - assertEquals("user.pan.peter", user.getAnchor().get().getName(), "unexpected anchor"); - } - - @Test - void testSetAnchorString() { - User user = this.createBuilderWithRequiredValues() - .anchor("user.pan.peter") - .build(); - assertEquals("user.pan.peter", user.getAnchor().get().getName(), "unexpected anchor"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testToBuilder() { - User user = User.builder() - .id("100560100000014842") - .anchor("user.peterpan") - .firstname("Peter") - .lastname("Pan") - .login("peterpan") - .note("Test") - .build(); - - User changedUser = user.toBuilder() - .build(); - - assertEquals("100560100000014842", changedUser.getId().get(), "unexpected id"); - assertEquals(Optional.of(Anchor.ofString("user.peterpan")), changedUser.getAnchor(), "unexpected anchor"); - assertEquals(Optional.of("Peter"), changedUser.getFirstname(), "unexpected firstname"); - assertEquals(Optional.of("Pan"), changedUser.getLastname(), "unexpected lastname"); - assertEquals("peterpan", changedUser.getLogin(), "unexpected login"); - assertEquals(Optional.of("Test"), changedUser.getNote(), "unexpected note"); - } - - @Test - void testSetFirstname() { - User user = this.createBuilderWithRequiredValues() - .firstname("Peter") - .build(); - assertEquals("Peter", user.getFirstname().get(), "unexpected firstname"); - } - - @Test - void testSetFirstnameWithNull() { - User user = this.createBuilderWithRequiredValues() - .firstname(null) - .build(); - assertTrue(user.getFirstname().isEmpty(), "firstname should be empty"); - } - - @Test - void testSetFirstnameWithBlank() { - User user = this.createBuilderWithRequiredValues() - .firstname(" ") - .build(); - assertTrue(user.getFirstname().isEmpty(), "firstname should be empty"); - } - - @Test - void testSetLastname() { - User user = this.createBuilderWithRequiredValues() - .lastname("Pan") - .build(); - assertEquals("Pan", user.getLastname().get(), "unexpected lastname"); - } - - @Test - void testSetLastnameWithNull() { - User user = this.createBuilderWithRequiredValues() - .lastname(null) - .build(); - assertTrue(user.getLastname().isEmpty(), "lastname should be empty"); - } - - @Test - void testSetLastnameWithBlank() { - User user = this.createBuilderWithRequiredValues() - .lastname(" ") - .build(); - assertTrue(user.getLastname().isEmpty(), "lastname should be empty"); - } - - @Test - void testGetNameOnlyLastname() { - User user = this.createBuilderWithRequiredValues() - .lastname("Pan") - .build(); - assertEquals("Pan", user.getName(), "unexpected name"); - } - - @Test - void testGetNameOnlyFirstname() { - User user = this.createBuilderWithRequiredValues() - .firstname("Peter") - .build(); - assertEquals("Peter", user.getName(), "unexpected name"); - } - - @Test - void testGetNameFirstnameAndLastName() { - User user = this.createBuilderWithRequiredValues() - .lastname("Pan") - .firstname("Peter") - .build(); - assertEquals("Pan, Peter", user.getName(), "unexpected name"); - } - - @Test - void testSetEmail() { - User user = this.createBuilderWithRequiredValues() - .email("peter.pan@nimmer.land") - .build(); - assertEquals("peter.pan@nimmer.land", user.getEmail().get(), "unexpected lastname"); - } - - @Test - void testSetEmailWithNull() { - User user = this.createBuilderWithRequiredValues() - .email(null) - .build(); - assertTrue(user.getEmail().isEmpty(), "email should be empty"); - } - - @Test - void testSetEmailWithBlank() { - User user = User.builder() - .login("test") - .email(" ") - .build(); - assertTrue(user.getEmail().isEmpty(), "email should be empty"); - } - - @Test - void testSetRoleListAsList() { - User user = this.createBuilderWithRequiredValues() - .roleList(Arrays.asList(Ref.ofId("123"))) - .build(); - assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); - } - - @Test - void testSetOverwriteRoleListAsList() { - User user = this.createBuilderWithRequiredValues() - .roleList(Arrays.asList(Ref.ofId("123"))) - .build(); - User overwritter = user.toBuilder() - .roleList(Arrays.asList(Ref.ofId("345"))) - .build(); - assertEquals(Arrays.asList(Ref.ofId("345")), overwritter.getRoleList(), "unexpected roleList"); - } - - @Test - void testSetNullRoleListAsList() { - assertThrows(NullPointerException.class, () -> { - User.builder().roleList((List)null); - }); - } - - @Test - void testSetNullRoleInList() { - assertThrows(NullPointerException.class, () -> { - User.builder().roleList(Arrays.asList(Ref.ofId("345"), null)); - }); - } - - @Test - void testSetRoleListAsVArgs() { - User user = this.createBuilderWithRequiredValues() - .roleList(Ref.ofId("123")) - .build(); - assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); - } - - @Test - void testSetOverwriteRoleListAsVArgs() { - User user = this.createBuilderWithRequiredValues() - .roleList(Ref.ofId("123")) - .build(); - User overwritter = user.toBuilder() - .roleList(Ref.ofId("345")) - .build(); - assertEquals(Arrays.asList(Ref.ofId("345")), overwritter.getRoleList(), "unexpected roleList"); - } - - @Test - void testSetNullRoleListAsVArgs() { - assertThrows(NullPointerException.class, () -> { - User.builder().roleList((Role[])null); - }); - } - - @Test - void testSetNullRoleInVArgs() { - assertThrows(NullPointerException.class, () -> { - User.builder().roleList(Ref.ofId("345"), null); - }); - } - - @Test - void testSetRole() { - User user = this.createBuilderWithRequiredValues() - .role(Ref.ofId("123")) - .build(); - assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); - } - - @Test - void testAddRole() { - User user = this.createBuilderWithRequiredValues() - .role(Ref.ofId("123")) - .build(); - User added = user.toBuilder() - .role(Ref.ofId("456")) - .build(); - - List expected = Arrays.asList(Ref.ofId("123"), Ref.ofId("456")); - - assertEquals(expected, added.getRoleList(), "unexpected roleList"); - } - - @Test - void testSetNullRole() { - assertThrows(NullPointerException.class, () -> { - User.builder().role(null); - }); - } - - @Test - void testSetIdentityListAsList() { - User user = this.createBuilderWithRequiredValues() - .identityList(Arrays.asList(TEST_IDENTITY)) - .build(); - assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); - } - - @Test - void testSetOverwriteIdentityListAsList() { - User user = this.createBuilderWithRequiredValues() - .identityList(Arrays.asList(TEST_IDENTITY)) - .build(); - Identity newIdentity = LdapIdentity.builder() - .server(3) - .dn("userdn2") - .build(); - User overwritter = user.toBuilder() - .identityList(Arrays.asList(newIdentity)) - .build(); - assertEquals(Arrays.asList(newIdentity), overwritter.getIdentityList(), "unexpected identityList"); - } - - @Test - void testSetNullIdentityListAsList() { - assertThrows(NullPointerException.class, () -> { - User.builder().identityList((List)null); - }); - } - - @Test - void testSetNullIdentityInList() { - assertThrows(NullPointerException.class, () -> { - User.builder().identityList(Arrays.asList(TEST_IDENTITY, null)); - }); - } - - @Test - void testSetIdentityListAsVArgs() { - User user = this.createBuilderWithRequiredValues() - .identityList(TEST_IDENTITY) - .build(); - assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); - } - - @Test - void testSetOverwriteIdentityListAsVArgs() { - User user = this.createBuilderWithRequiredValues() - .identityList(TEST_IDENTITY) - .build(); - Identity newIdentity = LdapIdentity.builder() - .server(3) - .dn("userdn2") - .build(); - User overwritter = user.toBuilder() - .identityList(newIdentity) - .build(); - assertEquals(Arrays.asList(newIdentity), overwritter.getIdentityList(), "unexpected identityList"); - } - - @Test - void testSetNullIdentityListAsVArgs() { - assertThrows(NullPointerException.class, () -> { - User.builder().identityList((Identity[])null); - }); - } - - @Test - void testSetNullIdentityInVArgs() { - assertThrows(NullPointerException.class, () -> { - User.builder().identityList(TEST_IDENTITY, null); - }); - } - - @Test - void testSetIndentity() { - User user = this.createBuilderWithRequiredValues() - .identity(TEST_IDENTITY) - .build(); - assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); - } - - @Test - void testAddIdentity() { - User user = this.createBuilderWithRequiredValues() - .identity(TEST_IDENTITY) - .build(); - - Identity newIdentity = LdapIdentity.builder() - .server(3) - .dn("userdn2") - .build(); - - User added = user.toBuilder() - .identity(newIdentity) - .build(); - - List expected = Arrays.asList(TEST_IDENTITY, newIdentity); - - assertEquals(expected, added.getIdentityList(), "unexpected roleList"); - } - - @Test - void testSetNullIdentity() { - assertThrows(NullPointerException.class, () -> { - User.builder().identity(null); - }); - } - - @Test - void testGetIdentity() { - Identity otherIdentity = mock(Identity.class); - User user = this.createBuilderWithRequiredValues() - .identity(otherIdentity) - .identity(TEST_IDENTITY) - .build(); - Optional identity = user.getIdentity(LdapIdentity.class); - assertEquals(TEST_IDENTITY, identity.get(), "unexpected identity"); - } - - @Test - void testGetUnknownIdentity() { - User user = this.createBuilderWithRequiredValues() - .build(); - Optional identity = user.getIdentity(LdapIdentity.class); - assertTrue(identity.isEmpty(), "identity should be empty"); - } - - @Test - void testDefaultGender() { - User user = this.createBuilderWithRequiredValues() - .build(); - assertEquals(GenderType.UNKNOWN, user.getGender(), "unexpected gender"); - } - - @Test - void testSetGender() { - User user = this.createBuilderWithRequiredValues() - .gender(GenderType.MALE) - .build(); - assertEquals(GenderType.MALE, user.getGender(), "unexpected gender"); - } - - @Test - void testSetGenderWithNull() { - assertThrows(NullPointerException.class, () -> { - User.builder().gender(null); - }); - } - - @Test - void testSetValiditiy() { - - User user = this.createBuilderWithRequiredValues() - .validity(UserValidity.builder() - .blocked(true) - .build() - ) - .build(); - - assertTrue(user.getValidity().isBlocked(), "user should be blocked"); - } - - @Test - void testSetValiditiyBuilder() { - - User user = this.createBuilderWithRequiredValues() - .validity(UserValidity.builder() - .blocked(true) - ) - .build(); - - assertTrue(user.getValidity().isBlocked(), "user should be blocked"); - } - - @Test - void testSetNullValiditiy() { - assertThrows(NullPointerException.class, () -> { - User.builder().validity((UserValidity)null); - }); - } - - @Test - void testSetNullValiditiyBuilder() { - assertThrows(NullPointerException.class, () -> { - User.builder().validity((UserValidity.Builder)null); - }); - } - - @Test - void testToString() { - User user = User.builder() - .id("100560100000014842") - .anchor("user.peterpan") - .firstname("Peter") - .lastname("Pan") - .email("peter.pan@nimmer.land") - .gender(GenderType.MALE) - .login("peterpan") - .roleList( - UserLevelRoles.USER, - Ref.ofAnchor("test.anchor"), - Ref.ofId("123")) - .identity(TEST_IDENTITY) - .note("a note") - .build(); - String expected = "User [id=100560100000014842, anchor=user.peterpan, login=peterpan, " + - "firstname=Peter, lastname=Pan, email=peter.pan@nimmer.land, gender=MALE, " + - "note=a note, validity=UserValidity [blocked=false, validFrom=null, validTo=null], " + - "identityList=[LdapIdentity [server=2, dn=userdn]], " + - "roleList=[USER, REF(test.anchor), REF(123)]]"; - assertEquals(expected, user.toString(), "unexpected string representation"); - } - - @Test - void testSerialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - - User user = User.builder() - .id("100560100000014842") - .anchor("user.peterpan") - .firstname("Peter") - .lastname("Pan") - .email("peter.pan@nimmer.land") - .gender(GenderType.MALE) - .login("peterpan") - .roleList( - UserLevelRoles.USER, - Ref.ofAnchor("test.anchor"), - Ref.ofId("123")) - .identity(TEST_IDENTITY) - .note("a note") - .build(); - - String json = mapper.writeValueAsString(user); - - String expected = "{\"id\":\"100560100000014842\"," + - "\"anchor\":\"user.peterpan\"," + - "\"login\":\"peterpan\"," + - "\"firstname\":\"Peter\"," + - "\"lastname\":\"Pan\"," + - "\"email\":\"peter.pan@nimmer.land\"," + - "\"gender\":\"MALE\"," + - "\"note\":\"a note\"," + - "\"validity\":{\"blocked\":false}," + - "\"identityList\":[{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}]," + - "\"roleList\":[\"USER\",\"REF(test.anchor)\",\"REF(123)\"]}"; - - assertEquals(expected, json, "unexpected json"); - } - - @Test - void testDeserialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - SimpleModule module = new SimpleModule(); - mapper.registerModule(module); - - String json = "{" + - "\"id\":100560100000014842," + - "\"anchor\":\"user.peterpan\"," + - "\"login\":\"peterpan\"," + - "\"firstname\":\"Peter\"," + - "\"lastname\":\"Pan\"," + - "\"email\":\"peter.pan@nimmer.land\"," + - "\"gender\":\"MALE\"," + - "\"note\":\"a note\"," + - "\"identityList\":[{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}]," + - "\"roleList\":[\"USER\",\"REF(test.anchor)\",\"REF(123)\"]" + - "}"; - - User user = mapper.readValue(json, User.class); - - User expected = User.builder() - .id("100560100000014842") - .anchor("user.peterpan") - .firstname("Peter") - .lastname("Pan") - .email("peter.pan@nimmer.land") - .gender(GenderType.MALE) - .login("peterpan") - .roleList( - UserLevelRoles.USER, - Ref.ofAnchor("test.anchor"), - Ref.ofId("123")) - .identity(TEST_IDENTITY) - .note("a note") - .build(); - - assertEquals(expected, user, "unexpected user"); - } - - private User.Builder createBuilderWithRequiredValues() { - return User.builder() - .login("test"); - } + private static Identity TEST_IDENTITY = LdapIdentity.builder().server(2).dn("userdn").build(); + + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(User.class).verify(); + } + + @Test + void testBuildWithoutLogin() { + assertThrows( + IllegalStateException.class, + () -> { + User.builder().build(); + }); + } + + @Test + void testSetLogin() { + User user = User.builder().login("peterpan").build(); + assertEquals("peterpan", user.getLogin(), "unexpected login"); + } + + @Test + void testSetIdentifierWithId() { + Identifier id = Identifier.ofId("123"); + User user = this.createBuilderWithRequiredValues().identifier(id).build(); + assertEquals("123", user.getId().get(), "unexpected id"); + } + + @Test + void testSetIdentifierWithAnchor() { + Identifier anchor = Identifier.ofAnchor(Anchor.ofString("abc")); + User user = this.createBuilderWithRequiredValues().identifier(anchor).build(); + assertEquals("abc", user.getAnchor().get().getName(), "unexpected anchor"); + } + + @Test + void testSetId() { + User user = this.createBuilderWithRequiredValues().id("123").build(); + assertEquals("123", user.getId().get(), "unexpected id"); + } + + @Test + void testGetEmptyId() { + User user = this.createBuilderWithRequiredValues().build(); + assertTrue(user.getId().isEmpty(), "id should be empty"); + } + + @Test + void testGetIdentifierWithId() { + User user = this.createBuilderWithRequiredValues().id("123").build(); + assertEquals(Identifier.ofId("123"), user.getIdentifier().get(), "unexpected identifier"); + } + + @Test + void testGetIdentifierWithAnchor() { + User user = this.createBuilderWithRequiredValues().anchor("abc").build(); + assertEquals( + Identifier.ofAnchor(Anchor.ofString("abc")), + user.getIdentifier().get(), + "unexpected identifier"); + } + + @Test + void testGetEmptyIdentifier() { + User user = this.createBuilderWithRequiredValues().build(); + assertTrue(user.getIdentifier().isEmpty(), "identifier should be empty"); + } + + @Test + void testSetIdWithZero() { + assertThrows( + IllegalArgumentException.class, + () -> { + User.builder().id("0"); + }, + "id 0 should't be allowed"); + } + + @Test + void testSetIdWithNull() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().id(null); + }, + "null should't be allowed"); + } + + @Test + void testSeIdWithInvalidValue() { + assertThrows( + IllegalArgumentException.class, + () -> { + User.builder().id("0x"); + }, + "invalid id should't be allowed"); + } + + @Test + void testSetAnchor() { + Anchor anchor = Anchor.ofString("user.pan.peter"); + User user = this.createBuilderWithRequiredValues().anchor(anchor).build(); + assertEquals("user.pan.peter", user.getAnchor().get().getName(), "unexpected anchor"); + } + + @Test + void testSetAnchorString() { + User user = this.createBuilderWithRequiredValues().anchor("user.pan.peter").build(); + assertEquals("user.pan.peter", user.getAnchor().get().getName(), "unexpected anchor"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testToBuilder() { + User user = + User.builder() + .id("100560100000014842") + .anchor("user.peterpan") + .firstname("Peter") + .lastname("Pan") + .login("peterpan") + .note("Test") + .build(); + + User changedUser = user.toBuilder().build(); + + assertEquals("100560100000014842", changedUser.getId().get(), "unexpected id"); + assertEquals( + Optional.of(Anchor.ofString("user.peterpan")), + changedUser.getAnchor(), + "unexpected anchor"); + assertEquals(Optional.of("Peter"), changedUser.getFirstname(), "unexpected firstname"); + assertEquals(Optional.of("Pan"), changedUser.getLastname(), "unexpected lastname"); + assertEquals("peterpan", changedUser.getLogin(), "unexpected login"); + assertEquals(Optional.of("Test"), changedUser.getNote(), "unexpected note"); + } + + @Test + void testSetFirstname() { + User user = this.createBuilderWithRequiredValues().firstname("Peter").build(); + assertEquals("Peter", user.getFirstname().get(), "unexpected firstname"); + } + + @Test + void testSetFirstnameWithNull() { + User user = this.createBuilderWithRequiredValues().firstname(null).build(); + assertTrue(user.getFirstname().isEmpty(), "firstname should be empty"); + } + + @Test + void testSetFirstnameWithBlank() { + User user = this.createBuilderWithRequiredValues().firstname(" ").build(); + assertTrue(user.getFirstname().isEmpty(), "firstname should be empty"); + } + + @Test + void testSetLastname() { + User user = this.createBuilderWithRequiredValues().lastname("Pan").build(); + assertEquals("Pan", user.getLastname().get(), "unexpected lastname"); + } + + @Test + void testSetLastnameWithNull() { + User user = this.createBuilderWithRequiredValues().lastname(null).build(); + assertTrue(user.getLastname().isEmpty(), "lastname should be empty"); + } + + @Test + void testSetLastnameWithBlank() { + User user = this.createBuilderWithRequiredValues().lastname(" ").build(); + assertTrue(user.getLastname().isEmpty(), "lastname should be empty"); + } + + @Test + void testGetNameOnlyLastname() { + User user = this.createBuilderWithRequiredValues().lastname("Pan").build(); + assertEquals("Pan", user.getName(), "unexpected name"); + } + + @Test + void testGetNameOnlyFirstname() { + User user = this.createBuilderWithRequiredValues().firstname("Peter").build(); + assertEquals("Peter", user.getName(), "unexpected name"); + } + + @Test + void testGetNameFirstnameAndLastName() { + User user = this.createBuilderWithRequiredValues().lastname("Pan").firstname("Peter").build(); + assertEquals("Pan, Peter", user.getName(), "unexpected name"); + } + + @Test + void testSetEmail() { + User user = this.createBuilderWithRequiredValues().email("peter.pan@nimmer.land").build(); + assertEquals("peter.pan@nimmer.land", user.getEmail().get(), "unexpected lastname"); + } + + @Test + void testSetEmailWithNull() { + User user = this.createBuilderWithRequiredValues().email(null).build(); + assertTrue(user.getEmail().isEmpty(), "email should be empty"); + } + + @Test + void testSetEmailWithBlank() { + User user = User.builder().login("test").email(" ").build(); + assertTrue(user.getEmail().isEmpty(), "email should be empty"); + } + + @Test + void testSetRoleListAsList() { + User user = + this.createBuilderWithRequiredValues().roleList(Arrays.asList(Ref.ofId("123"))).build(); + assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); + } + + @Test + void testSetOverwriteRoleListAsList() { + User user = + this.createBuilderWithRequiredValues().roleList(Arrays.asList(Ref.ofId("123"))).build(); + User overwritter = user.toBuilder().roleList(Arrays.asList(Ref.ofId("345"))).build(); + assertEquals(Arrays.asList(Ref.ofId("345")), overwritter.getRoleList(), "unexpected roleList"); + } + + @Test + void testSetNullRoleListAsList() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().roleList((List) null); + }); + } + + @Test + void testSetNullRoleInList() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().roleList(Arrays.asList(Ref.ofId("345"), null)); + }); + } + + @Test + void testSetRoleListAsVArgs() { + User user = this.createBuilderWithRequiredValues().roleList(Ref.ofId("123")).build(); + assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); + } + + @Test + void testSetOverwriteRoleListAsVArgs() { + User user = this.createBuilderWithRequiredValues().roleList(Ref.ofId("123")).build(); + User overwritter = user.toBuilder().roleList(Ref.ofId("345")).build(); + assertEquals(Arrays.asList(Ref.ofId("345")), overwritter.getRoleList(), "unexpected roleList"); + } + + @Test + void testSetNullRoleListAsVArgs() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().roleList((Role[]) null); + }); + } + + @Test + void testSetNullRoleInVArgs() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().roleList(Ref.ofId("345"), null); + }); + } + + @Test + void testSetRole() { + User user = this.createBuilderWithRequiredValues().role(Ref.ofId("123")).build(); + assertEquals(Arrays.asList(Ref.ofId("123")), user.getRoleList(), "unexpected roleList"); + } + + @Test + void testAddRole() { + User user = this.createBuilderWithRequiredValues().role(Ref.ofId("123")).build(); + User added = user.toBuilder().role(Ref.ofId("456")).build(); + + List expected = Arrays.asList(Ref.ofId("123"), Ref.ofId("456")); + + assertEquals(expected, added.getRoleList(), "unexpected roleList"); + } + + @Test + void testSetNullRole() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().role(null); + }); + } + + @Test + void testSetIdentityListAsList() { + User user = + this.createBuilderWithRequiredValues().identityList(Arrays.asList(TEST_IDENTITY)).build(); + assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); + } + + @Test + void testSetOverwriteIdentityListAsList() { + User user = + this.createBuilderWithRequiredValues().identityList(Arrays.asList(TEST_IDENTITY)).build(); + Identity newIdentity = LdapIdentity.builder().server(3).dn("userdn2").build(); + User overwritter = user.toBuilder().identityList(Arrays.asList(newIdentity)).build(); + assertEquals( + Arrays.asList(newIdentity), overwritter.getIdentityList(), "unexpected identityList"); + } + + @Test + void testSetNullIdentityListAsList() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().identityList((List) null); + }); + } + + @Test + void testSetNullIdentityInList() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().identityList(Arrays.asList(TEST_IDENTITY, null)); + }); + } + + @Test + void testSetIdentityListAsVArgs() { + User user = this.createBuilderWithRequiredValues().identityList(TEST_IDENTITY).build(); + assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); + } + + @Test + void testSetOverwriteIdentityListAsVArgs() { + User user = this.createBuilderWithRequiredValues().identityList(TEST_IDENTITY).build(); + Identity newIdentity = LdapIdentity.builder().server(3).dn("userdn2").build(); + User overwritter = user.toBuilder().identityList(newIdentity).build(); + assertEquals( + Arrays.asList(newIdentity), overwritter.getIdentityList(), "unexpected identityList"); + } + + @Test + void testSetNullIdentityListAsVArgs() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().identityList((Identity[]) null); + }); + } + + @Test + void testSetNullIdentityInVArgs() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().identityList(TEST_IDENTITY, null); + }); + } + + @Test + void testSetIndentity() { + User user = this.createBuilderWithRequiredValues().identity(TEST_IDENTITY).build(); + assertEquals(Arrays.asList(TEST_IDENTITY), user.getIdentityList(), "unexpected identityList"); + } + + @Test + void testAddIdentity() { + User user = this.createBuilderWithRequiredValues().identity(TEST_IDENTITY).build(); + + Identity newIdentity = LdapIdentity.builder().server(3).dn("userdn2").build(); + + User added = user.toBuilder().identity(newIdentity).build(); + + List expected = Arrays.asList(TEST_IDENTITY, newIdentity); + + assertEquals(expected, added.getIdentityList(), "unexpected roleList"); + } + + @Test + void testSetNullIdentity() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().identity(null); + }); + } + + @Test + void testGetIdentity() { + Identity otherIdentity = mock(Identity.class); + User user = + this.createBuilderWithRequiredValues() + .identity(otherIdentity) + .identity(TEST_IDENTITY) + .build(); + Optional identity = user.getIdentity(LdapIdentity.class); + assertEquals(TEST_IDENTITY, identity.get(), "unexpected identity"); + } + + @Test + void testGetUnknownIdentity() { + User user = this.createBuilderWithRequiredValues().build(); + Optional identity = user.getIdentity(LdapIdentity.class); + assertTrue(identity.isEmpty(), "identity should be empty"); + } + + @Test + void testDefaultGender() { + User user = this.createBuilderWithRequiredValues().build(); + assertEquals(GenderType.UNKNOWN, user.getGender(), "unexpected gender"); + } + + @Test + void testSetGender() { + User user = this.createBuilderWithRequiredValues().gender(GenderType.MALE).build(); + assertEquals(GenderType.MALE, user.getGender(), "unexpected gender"); + } + + @Test + void testSetGenderWithNull() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().gender(null); + }); + } + + @Test + void testSetValiditiy() { + + User user = + this.createBuilderWithRequiredValues() + .validity(UserValidity.builder().blocked(true).build()) + .build(); + + assertTrue(user.getValidity().isBlocked(), "user should be blocked"); + } + + @Test + void testSetValiditiyBuilder() { + + User user = + this.createBuilderWithRequiredValues() + .validity(UserValidity.builder().blocked(true)) + .build(); + + assertTrue(user.getValidity().isBlocked(), "user should be blocked"); + } + + @Test + void testSetNullValiditiy() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().validity((UserValidity) null); + }); + } + + @Test + void testSetNullValiditiyBuilder() { + assertThrows( + NullPointerException.class, + () -> { + User.builder().validity((UserValidity.Builder) null); + }); + } + + @Test + void testToString() { + User user = + User.builder() + .id("100560100000014842") + .anchor("user.peterpan") + .firstname("Peter") + .lastname("Pan") + .email("peter.pan@nimmer.land") + .gender(GenderType.MALE) + .login("peterpan") + .roleList(UserLevelRoles.USER, Ref.ofAnchor("test.anchor"), Ref.ofId("123")) + .identity(TEST_IDENTITY) + .note("a note") + .build(); + String expected = + """ + User [id=100560100000014842, anchor=user.peterpan, login=peterpan,\s\ + firstname=Peter, lastname=Pan, email=peter.pan@nimmer.land, gender=MALE,\s\ + note=a note, validity=UserValidity [blocked=false, validFrom=null, validTo=null],\s\ + identityList=[LdapIdentity [server=2, dn=userdn]],\s\ + roleList=[USER, REF(test.anchor), REF(123)]]"""; + assertEquals(expected, user.toString(), "unexpected string representation"); + } + + @Test + void testSerialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + + User user = + User.builder() + .id("100560100000014842") + .anchor("user.peterpan") + .firstname("Peter") + .lastname("Pan") + .email("peter.pan@nimmer.land") + .gender(GenderType.MALE) + .login("peterpan") + .roleList(UserLevelRoles.USER, Ref.ofAnchor("test.anchor"), Ref.ofId("123")) + .identity(TEST_IDENTITY) + .note("a note") + .build(); + + String json = mapper.writeValueAsString(user); + + String expected = + """ + {"id":"100560100000014842",\ + "anchor":"user.peterpan",\ + "login":"peterpan",\ + "firstname":"Peter",\ + "lastname":"Pan",\ + "email":"peter.pan@nimmer.land",\ + "gender":"MALE",\ + "note":"a note",\ + "validity":{"blocked":false},\ + "identityList":[{"@type":"ldap","server":2,"dn":"userdn"}],\ + "roleList":["USER","REF(test.anchor)","REF(123)"]}"""; + + assertEquals(expected, json, "unexpected json"); + } + + @Test + void testDeserialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + SimpleModule module = new SimpleModule(); + mapper.registerModule(module); + + String json = + """ + {\ + "id":100560100000014842,\ + "anchor":"user.peterpan",\ + "login":"peterpan",\ + "firstname":"Peter",\ + "lastname":"Pan",\ + "email":"peter.pan@nimmer.land",\ + "gender":"MALE",\ + "note":"a note",\ + "identityList":[{"@type":"ldap","server":2,"dn":"userdn"}],\ + "roleList":["USER","REF(test.anchor)","REF(123)"]\ + }"""; + + User user = mapper.readValue(json, User.class); + + User expected = + User.builder() + .id("100560100000014842") + .anchor("user.peterpan") + .firstname("Peter") + .lastname("Pan") + .email("peter.pan@nimmer.land") + .gender(GenderType.MALE) + .login("peterpan") + .roleList(UserLevelRoles.USER, Ref.ofAnchor("test.anchor"), Ref.ofId("123")) + .identity(TEST_IDENTITY) + .note("a note") + .build(); + + assertEquals(expected, user, "unexpected user"); + } + + private User.Builder createBuilderWithRequiredValues() { + return User.builder().login("test"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidityTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidityTest.java index a4a8a94..c891794 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidityTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/UserValidityTest.java @@ -5,273 +5,276 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; - -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals", - "PMD.TooManyMethods" + "PMD.JUnitTestContainsTooManyAsserts", + "PMD.AvoidDuplicateLiterals", + "PMD.TooManyMethods" }) @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL", - "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL", + "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" }) class UserValidityTest { - private static final ZoneId ZONE_ID = ZoneId.of( "Europe/Berlin" ); - - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(UserValidity.class) - .verify(); - } - - @Test - void testToBuilder() throws JsonProcessingException { - - OffsetDateTime validFrom = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validTo = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - UserValidity userValidity = UserValidity.builder() - .blocked(false) - .validFrom(validFrom) - .validTo(validTo) - .build(); - - UserValidity copyOfUserValidity = userValidity.toBuilder() - .build(); - - assertFalse(copyOfUserValidity.isBlocked(), "blocked should be false"); - assertEquals(validFrom, userValidity.getValidFrom().get(), "unexpected validFrom"); - assertEquals(validTo, userValidity.getValidTo().get(), "unexpected validTo"); - } - - @Test - void testToString() throws JsonProcessingException { - - OffsetDateTime validFrom = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validTo = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - - UserValidity userValidity = UserValidity.builder() - .blocked(false) - .validFrom(validFrom) - .validTo(validTo) - .build(); + private static final ZoneId ZONE_ID = ZoneId.of("Europe/Berlin"); - String expecated = "UserValidity [blocked=false, validFrom=2023-08-21T00:00+02:00, " + - "validTo=2023-08-21T00:00+02:00]"; + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(UserValidity.class).verify(); + } - assertEquals(expecated, userValidity.toString(), "unexpected string representation"); - } + @Test + void testToBuilder() throws JsonProcessingException { - @Test - void testAlwaysValid() throws JsonProcessingException { + OffsetDateTime validFrom = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime validTo = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - UserValidity userValidity = UserValidity.ALWAYS_VALID; + UserValidity userValidity = + UserValidity.builder().blocked(false).validFrom(validFrom).validTo(validTo).build(); - assertFalse(userValidity.isBlocked(), "blocked should be false"); - assertTrue(userValidity.getValidFrom().isEmpty(), "validFrom should be empty"); - assertTrue(userValidity.getValidTo().isEmpty(), "validTo should be empty"); - } + UserValidity copyOfUserValidity = userValidity.toBuilder().build(); - @Test - void testIsNowValid() throws JsonProcessingException { + assertFalse(copyOfUserValidity.isBlocked(), "blocked should be false"); + assertEquals(validFrom, userValidity.getValidFrom().get(), "unexpected validFrom"); + assertEquals(validTo, userValidity.getValidTo().get(), "unexpected validTo"); + } - UserValidity userValidity = UserValidity.builder() - .blocked(false) - .build(); + @Test + void testToString() throws JsonProcessingException { - assertTrue(userValidity.isNowValid(), "validity should be valid"); - } + OffsetDateTime validFrom = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime validTo = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - @Test - void testIsValidWithNullBase() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - UserValidity.ALWAYS_VALID.isValid(null); - }); - } + UserValidity userValidity = + UserValidity.builder().blocked(false).validFrom(validFrom).validTo(validTo).build(); - @Test - void testIsValidBlocked() throws JsonProcessingException { + String expecated = + "UserValidity [blocked=false, validFrom=2023-08-21T00:00+02:00, " + + "validTo=2023-08-21T00:00+02:00]"; - UserValidity userValidity = UserValidity.builder() - .blocked(true) - .build(); + assertEquals(expecated, userValidity.toString(), "unexpected string representation"); + } - OffsetDateTime base = LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + @Test + void testAlwaysValid() throws JsonProcessingException { - assertFalse(userValidity.isValid(base), "validity should't be valid"); - } + UserValidity userValidity = UserValidity.ALWAYS_VALID; - @Test - void testIsValidFrom() throws JsonProcessingException { + assertFalse(userValidity.isBlocked(), "blocked should be false"); + assertTrue(userValidity.getValidFrom().isEmpty(), "validFrom should be empty"); + assertTrue(userValidity.getValidTo().isEmpty(), "validTo should be empty"); + } - OffsetDateTime validFrom = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + @Test + void testIsNowValid() throws JsonProcessingException { - OffsetDateTime base = LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().blocked(false).build(); - UserValidity userValidity = UserValidity.builder() - .validFrom(validFrom) - .build(); + assertTrue(userValidity.isNowValid(), "validity should be valid"); + } - assertTrue(userValidity.isValid(base), "validity should be valid"); - } + @Test + void testIsValidWithNullBase() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + UserValidity.ALWAYS_VALID.isValid(null); + }); + } - @Test - void testIsNotValidFrom() throws JsonProcessingException { + @Test + void testIsValidBlocked() throws JsonProcessingException { - OffsetDateTime validFrom = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().blocked(true).build(); - OffsetDateTime base = LocalDate.of(2023, 8, 20).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime base = + LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - UserValidity userValidity = UserValidity.builder() - .validFrom(validFrom) - .build(); + assertFalse(userValidity.isValid(base), "validity should't be valid"); + } - assertFalse(userValidity.isValid(base), "validity should not be valid"); - } + @Test + void testIsValidFrom() throws JsonProcessingException { - @Test - void testIsValidTo() throws JsonProcessingException { + OffsetDateTime validFrom = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validTo = LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime base = + LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime base = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().validFrom(validFrom).build(); - UserValidity userValidity = UserValidity.builder() - .validTo(validTo) - .build(); + assertTrue(userValidity.isValid(base), "validity should be valid"); + } - assertTrue(userValidity.isValid(base), "validity should be valid"); - } + @Test + void testIsNotValidFrom() throws JsonProcessingException { - @Test - void testIsNotValidTo() throws JsonProcessingException { + OffsetDateTime validFrom = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validTo = LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + OffsetDateTime base = + LocalDate.of(2023, 8, 20).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime base = LocalDate.of(2023, 9, 1).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().validFrom(validFrom).build(); - UserValidity userValidity = UserValidity.builder() - .validTo(validTo) - .build(); + assertFalse(userValidity.isValid(base), "validity should not be valid"); + } - assertFalse(userValidity.isValid(base), "validity should not be valid"); - } + @Test + void testIsValidTo() throws JsonProcessingException { + OffsetDateTime validTo = + LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - @Test - void testSetValidFrom() throws JsonProcessingException { + OffsetDateTime base = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validFrom = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().validTo(validTo).build(); - UserValidity userValidity = UserValidity.builder() - .validFrom(validFrom) - .build(); + assertTrue(userValidity.isValid(base), "validity should be valid"); + } - assertFalse(userValidity.isBlocked(), "blocked should be false"); - assertEquals(validFrom, userValidity.getValidFrom().get(), "unexpected validFrom"); - assertTrue(userValidity.getValidTo().isEmpty(), "validTo should be empty"); - } + @Test + void testIsNotValidTo() throws JsonProcessingException { - @Test - void testSetValidFromToNull() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - UserValidity.builder().validFrom(null); - }); - } + OffsetDateTime validTo = + LocalDate.of(2023, 8, 30).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - @Test - void testSetValidTo() throws JsonProcessingException { + OffsetDateTime base = + LocalDate.of(2023, 9, 1).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - OffsetDateTime validTo = LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); + UserValidity userValidity = UserValidity.builder().validTo(validTo).build(); - UserValidity userValidity = UserValidity.builder() - .validTo(validTo) - .build(); + assertFalse(userValidity.isValid(base), "validity should not be valid"); + } - assertFalse(userValidity.isBlocked(), "blocked should be false"); - assertTrue(userValidity.getValidFrom().isEmpty(), "validFrom should be empty"); - assertEquals(validTo, userValidity.getValidTo().get(), "unexpected validTo"); - } + @Test + void testSetValidFrom() throws JsonProcessingException { - @Test - void testSetValidToToNull() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - UserValidity.builder().validTo(null); - }); - } + OffsetDateTime validFrom = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - @Test - void testSerialize() throws JsonProcessingException { + UserValidity userValidity = UserValidity.builder().validFrom(validFrom).build(); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + assertFalse(userValidity.isBlocked(), "blocked should be false"); + assertEquals(validFrom, userValidity.getValidFrom().get(), "unexpected validFrom"); + assertTrue(userValidity.getValidTo().isEmpty(), "validTo should be empty"); + } - UserValidity userValidity = UserValidity.builder() - .blocked(false) - .validFrom(LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime()) - .validTo(LocalDate.of(2023, 10, 1).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime()) - .build(); + @Test + void testSetValidFromToNull() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + UserValidity.builder().validFrom(null); + }); + } - String json = mapper.writeValueAsString(userValidity); + @Test + void testSetValidTo() throws JsonProcessingException { - String expected = "{" + - "\"blocked\":false," + - "\"validFrom\":\"2023-08-21T00:00:00+02:00\"," + - "\"validTo\":\"2023-10-01T00:00:00+02:00\"}"; + OffsetDateTime validTo = + LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime(); - assertEquals(expected, json, "unexpected json"); - } + UserValidity userValidity = UserValidity.builder().validTo(validTo).build(); - @Test - void testDeserialize() throws JsonProcessingException { + assertFalse(userValidity.isBlocked(), "blocked should be false"); + assertTrue(userValidity.getValidFrom().isEmpty(), "validFrom should be empty"); + assertEquals(validTo, userValidity.getValidTo().get(), "unexpected validTo"); + } - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + @Test + void testSetValidToToNull() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + UserValidity.builder().validTo(null); + }); + } - String json = "{" + - "\"blocked\":false," + - "\"validFrom\":\"2023-08-21T00:00:00+02:00\"," + - "\"validTo\":\"2023-10-01T00:00:00+02:00\"}"; + @Test + void testSerialize() throws JsonProcessingException { - UserValidity userValidity = mapper.readValue(json, UserValidity.class); + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - UserValidity expected = UserValidity.builder() - .blocked(false) - .validFrom(LocalDate.of(2023, 8, 21) - .atStartOfDay() - .atZone(ZONE_ID).toOffsetDateTime() - .withOffsetSameInstant(ZoneOffset.UTC)) - .validTo(LocalDate.of(2023, 10, 1) - .atStartOfDay() - .atZone(ZONE_ID) - .toOffsetDateTime() - .withOffsetSameInstant(ZoneOffset.UTC)) - .build(); - - assertEquals(expected, userValidity, "unexpected userValidity"); - } + UserValidity userValidity = + UserValidity.builder() + .blocked(false) + .validFrom(LocalDate.of(2023, 8, 21).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime()) + .validTo(LocalDate.of(2023, 10, 1).atStartOfDay().atZone(ZONE_ID).toOffsetDateTime()) + .build(); + + String json = mapper.writeValueAsString(userValidity); + + String expected = + """ + {\ + "blocked":false,\ + "validFrom":"2023-08-21T00:00:00+02:00",\ + "validTo":"2023-10-01T00:00:00+02:00"}"""; + + assertEquals(expected, json, "unexpected json"); + } + + @Test + void testDeserialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + String json = + """ + {\ + "blocked":false,\ + "validFrom":"2023-08-21T00:00:00+02:00",\ + "validTo":"2023-10-01T00:00:00+02:00"}"""; + + UserValidity userValidity = mapper.readValue(json, UserValidity.class); + + UserValidity expected = + UserValidity.builder() + .blocked(false) + .validFrom( + LocalDate.of(2023, 8, 21) + .atStartOfDay() + .atZone(ZONE_ID) + .toOffsetDateTime() + .withOffsetSameInstant(ZoneOffset.UTC)) + .validTo( + LocalDate.of(2023, 10, 1) + .atStartOfDay() + .atZone(ZONE_ID) + .toOffsetDateTime() + .withOffsetSameInstant(ZoneOffset.UTC)) + .build(); + + assertEquals(expected, userValidity, "unexpected userValidity"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentityTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentityTest.java index c3ce621..266050f 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentityTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/identity/LdapIdentityTest.java @@ -3,143 +3,130 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.TooManyMethods") @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL", - "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL", + "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS" }) class LdapIdentityTest { - private static final String USER_DN = "userdn"; - - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(LdapIdentity.class) - .verify(); - } - - @Test - void testSetServer() throws JsonProcessingException { - LdapIdentity ldapIdentity = LdapIdentity.builder() - .server(2) - .dn(USER_DN) - .build(); - assertEquals(2, ldapIdentity.getServer(), "unexpected server"); - } - - @Test - void testSetInvalidServer() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - LdapIdentity.builder().server(0); - }); - } - - @Test - void testSetNullDn() throws JsonProcessingException { - assertThrows(NullPointerException.class, () -> { - LdapIdentity.builder().dn(null); - }); - } - - @Test - void testSetBlankdDn() throws JsonProcessingException { - assertThrows(IllegalArgumentException.class, () -> { - LdapIdentity.builder().dn(" "); - }); - } - - @Test - void testMissingServer() throws JsonProcessingException { - assertThrows(IllegalStateException.class, () -> { - LdapIdentity.builder() - .dn(USER_DN) - .build(); - }); - } - - @Test - void testMissingDn() throws JsonProcessingException { - assertThrows(IllegalStateException.class, () -> { - LdapIdentity.builder() - .server(1) - .build(); - }); - } - - @Test - void testSetDn() throws JsonProcessingException { - LdapIdentity ldapIdentity = LdapIdentity.builder() - .server(2) - .dn(USER_DN) - .build(); - assertEquals(USER_DN, ldapIdentity.getDn(), "unexpected server"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testToBuilder() throws JsonProcessingException { - - LdapIdentity ldapIdentity = LdapIdentity.builder() - .server(2) - .dn(USER_DN) - .build(); - - LdapIdentity changedLdapIdentity = ldapIdentity.toBuilder() - .build(); - - assertEquals(2, changedLdapIdentity.getServer(), "unexpected server"); - assertEquals(USER_DN, changedLdapIdentity.getDn(), "dn"); - } - - @Test - void testSerialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - - LdapIdentity ldapIdentity = LdapIdentity.builder() - .server(2) - .dn(USER_DN) - .build(); - - String json = mapper.writeValueAsString(ldapIdentity); - - String expected = "{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}"; - - assertEquals(expected, json, "unexpected json"); - } - - @Test - void testDeserialize() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new Jdk8Module()); - SimpleModule module = new SimpleModule(); - mapper.registerModule(module); - - String json = "{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}"; - - LdapIdentity ldapIdentity = mapper.readValue(json, LdapIdentity.class); - - LdapIdentity expected = LdapIdentity.builder() - .server(2) - .dn(USER_DN) - .build(); - - assertEquals(expected, ldapIdentity, "unexpected ldapIdentity"); - } + private static final String USER_DN = "userdn"; + + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(LdapIdentity.class).verify(); + } + + @Test + void testSetServer() throws JsonProcessingException { + LdapIdentity ldapIdentity = LdapIdentity.builder().server(2).dn(USER_DN).build(); + assertEquals(2, ldapIdentity.getServer(), "unexpected server"); + } + + @Test + void testSetInvalidServer() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + LdapIdentity.builder().server(0); + }); + } + + @Test + void testSetNullDn() throws JsonProcessingException { + assertThrows( + NullPointerException.class, + () -> { + LdapIdentity.builder().dn(null); + }); + } + + @Test + void testSetBlankdDn() throws JsonProcessingException { + assertThrows( + IllegalArgumentException.class, + () -> { + LdapIdentity.builder().dn(" "); + }); + } + + @Test + void testMissingServer() throws JsonProcessingException { + assertThrows( + IllegalStateException.class, + () -> { + LdapIdentity.builder().dn(USER_DN).build(); + }); + } + + @Test + void testMissingDn() throws JsonProcessingException { + assertThrows( + IllegalStateException.class, + () -> { + LdapIdentity.builder().server(1).build(); + }); + } + + @Test + void testSetDn() throws JsonProcessingException { + LdapIdentity ldapIdentity = LdapIdentity.builder().server(2).dn(USER_DN).build(); + assertEquals(USER_DN, ldapIdentity.getDn(), "unexpected server"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testToBuilder() throws JsonProcessingException { + + LdapIdentity ldapIdentity = LdapIdentity.builder().server(2).dn(USER_DN).build(); + + LdapIdentity changedLdapIdentity = ldapIdentity.toBuilder().build(); + + assertEquals(2, changedLdapIdentity.getServer(), "unexpected server"); + assertEquals(USER_DN, changedLdapIdentity.getDn(), "dn"); + } + + @Test + void testSerialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + + LdapIdentity ldapIdentity = LdapIdentity.builder().server(2).dn(USER_DN).build(); + + String json = mapper.writeValueAsString(ldapIdentity); + + String expected = "{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}"; + + assertEquals(expected, json, "unexpected json"); + } + + @Test + void testDeserialize() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Jdk8Module()); + SimpleModule module = new SimpleModule(); + mapper.registerModule(module); + + String json = "{\"@type\":\"ldap\",\"server\":2,\"dn\":\"userdn\"}"; + + LdapIdentity ldapIdentity = mapper.readValue(json, LdapIdentity.class); + + LdapIdentity expected = LdapIdentity.builder().server(2).dn(USER_DN).build(); + + assertEquals(expected, ldapIdentity, "unexpected ldapIdentity"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactoryTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactoryTest.java index 0f42d69..0ba2884 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactoryTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefFactoryTest.java @@ -9,45 +9,47 @@ class RefFactoryTest { - @Test - void testAcceptWithId() { - RefFactory factory = new RefFactory(); - assertTrue(factory.accept("REF(123)"), "should accepted"); - } - - @Test - void testAcceptWithAnchor() { - RefFactory factory = new RefFactory(); - assertTrue(factory.accept("REF(group.user)"), "should accepted"); - } - - @Test - void testNotAccept() { - RefFactory factory = new RefFactory(); - assertFalse(factory.accept("ADMINISTRATOR"), "should not accepted"); - } - - @Test - void testCreateWithId() { - RefFactory factory = new RefFactory(); - Ref ref = factory.create("REF(123)"); - assertEquals("123", ref.getId().get(), "unexpected id"); - assertTrue(ref.getAnchor().isEmpty(), "anchor should be empty"); - } - - @Test - void testCreateWithAnchor() { - RefFactory factory = new RefFactory(); - Ref ref = factory.create("REF(group.user)"); - assertEquals("group.user", ref.getAnchor().get().getName(), "unexpected anchor"); - assertTrue(ref.getId().isEmpty(), "id should be empty"); - } - - @Test - void testCreateInvalid() { - RefFactory factory = new RefFactory(); - assertThrows(IllegalArgumentException.class, () -> { - factory.create("GROUP(a/g)"); - }); - } + @Test + void testAcceptWithId() { + RefFactory factory = new RefFactory(); + assertTrue(factory.accept("REF(123)"), "should accepted"); + } + + @Test + void testAcceptWithAnchor() { + RefFactory factory = new RefFactory(); + assertTrue(factory.accept("REF(group.user)"), "should accepted"); + } + + @Test + void testNotAccept() { + RefFactory factory = new RefFactory(); + assertFalse(factory.accept("ADMINISTRATOR"), "should not accepted"); + } + + @Test + void testCreateWithId() { + RefFactory factory = new RefFactory(); + Ref ref = factory.create("REF(123)"); + assertEquals("123", ref.getId().get(), "unexpected id"); + assertTrue(ref.getAnchor().isEmpty(), "anchor should be empty"); + } + + @Test + void testCreateWithAnchor() { + RefFactory factory = new RefFactory(); + Ref ref = factory.create("REF(group.user)"); + assertEquals("group.user", ref.getAnchor().get().getName(), "unexpected anchor"); + assertTrue(ref.getId().isEmpty(), "id should be empty"); + } + + @Test + void testCreateInvalid() { + RefFactory factory = new RefFactory(); + assertThrows( + IllegalArgumentException.class, + () -> { + factory.create("GROUP(a/g)"); + }); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefTest.java index ab89f27..6c05b06 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/RefTest.java @@ -3,91 +3,91 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressFBWarnings({ - "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", - "NP_NULL_PARAM_DEREF_NONVIRTUAL" + "PI_DO_NOT_REUSE_PUBLIC_IDENTIFIERS_CLASS_NAMES", + "NP_NULL_PARAM_DEREF_NONVIRTUAL" }) class RefTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - void testEquals() { - EqualsVerifier.forClass(Ref.class) - .withIgnoredFields("id", "anchor") - .verify(); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + void testEquals() { + EqualsVerifier.forClass(Ref.class).withIgnoredFields("id", "anchor").verify(); + } - @Test - @SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" - }) - void testAnchorRef() { - Ref ref = Ref.ofAnchor(Anchor.ofString("role.a")); - assertEquals("REF(role.a)", ref.getName(), "unexpected name"); - assertEquals(Optional.empty(), ref.getId(), "empty id expected"); - assertEquals(Optional.of(Anchor.ofString("role.a")), ref.getAnchor(), "unexpected anchor"); - } + @Test + @SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) + void testAnchorRef() { + Ref ref = Ref.ofAnchor(Anchor.ofString("role.a")); + assertEquals("REF(role.a)", ref.getName(), "unexpected name"); + assertEquals(Optional.empty(), ref.getId(), "empty id expected"); + assertEquals(Optional.of(Anchor.ofString("role.a")), ref.getAnchor(), "unexpected anchor"); + } - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testAnchorStringRef() { - Ref ref = Ref.ofAnchor("role.a"); - assertEquals("REF(role.a)", ref.getName(), "unexpected name"); - assertEquals(Optional.empty(), ref.getId(), "empty id expected"); - assertEquals(Optional.of(Anchor.ofString("role.a")), ref.getAnchor(), "unexpected anchor"); - } + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testAnchorStringRef() { + Ref ref = Ref.ofAnchor("role.a"); + assertEquals("REF(role.a)", ref.getName(), "unexpected name"); + assertEquals(Optional.empty(), ref.getId(), "empty id expected"); + assertEquals(Optional.of(Anchor.ofString("role.a")), ref.getAnchor(), "unexpected anchor"); + } - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testNullAnchorRef() { - assertThrows(NullPointerException.class, () -> { - Ref.ofAnchor((Anchor)null); - }); - } + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testNullAnchorRef() { + assertThrows( + NullPointerException.class, + () -> { + Ref.ofAnchor((Anchor) null); + }); + } - @Test - void testNullAnchorStringRef() { - assertThrows(NullPointerException.class, () -> { - Ref.ofAnchor((String)null); - }); - } + @Test + void testNullAnchorStringRef() { + assertThrows( + NullPointerException.class, + () -> { + Ref.ofAnchor((String) null); + }); + } - @Test - void testNullIdRef() { - assertThrows(IllegalArgumentException.class, () -> { - Ref.ofId("0"); - }); - } + @Test + void testNullIdRef() { + assertThrows( + IllegalArgumentException.class, + () -> { + Ref.ofId("0"); + }); + } - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testIdRef() { - Ref ref = Ref.ofId("123"); - assertEquals("REF(123)", ref.getName(), "unexpected name"); - assertEquals(Optional.empty(), ref.getAnchor(), "empty anchor expected"); - assertEquals(Optional.of("123"), ref.getId(), "unexpected id"); - } + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testIdRef() { + Ref ref = Ref.ofId("123"); + assertEquals("REF(123)", ref.getName(), "unexpected name"); + assertEquals(Optional.empty(), ref.getAnchor(), "empty anchor expected"); + assertEquals(Optional.of("123"), ref.getId(), "unexpected id"); + } - @Test - void testIdRefWithInvalidId() { - assertThrows(IllegalArgumentException.class, () -> { - Ref.ofId("1x"); - }); - } + @Test + void testIdRefWithInvalidId() { + assertThrows( + IllegalArgumentException.class, + () -> { + Ref.ofId("1x"); + }); + } - @Test - void testWorkarroundConstructor() { - Ref ref = new Ref(); - assertEquals("NONE", ref.getName(), "unexpected role name"); - } + @Test + void testWorkarroundConstructor() { + Ref ref = new Ref(); + assertEquals("NONE", ref.getName(), "unexpected role name"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRolesTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRolesTest.java index 77ce78b..0513b30 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRolesTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/entity/role/UserLevelRolesTest.java @@ -3,38 +3,34 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Role; +import org.junit.jupiter.api.Test; class UserLevelRolesTest { - @Test - void testIsUserLevelRoleAdministrator() { - assertTrue( - UserLevelRoles.isUserLevelRole(Role.ofName("ADMINISTRATOR")), - "ADMINISTRATOR should be user level role"); - } - - @Test - void testIsUserLevelRoleUser() { - assertTrue( - UserLevelRoles.isUserLevelRole(Role.ofName("USER")), - "USER should be user level role"); - } - - @Test - void testIsUserLevelRoleExternal() { - assertTrue( - UserLevelRoles.isUserLevelRole(Role.ofName("EXTERNAL")), - "EXTERNAL should be user level role"); - } - - @Test - void testIsNotUserLevelRole() { - assertFalse( - UserLevelRoles.isUserLevelRole(Role.ofName("ABC")), - "ABC should't be user level role"); - } - + @Test + void testIsUserLevelRoleAdministrator() { + assertTrue( + UserLevelRoles.isUserLevelRole(Role.ofName("ADMINISTRATOR")), + "ADMINISTRATOR should be user level role"); + } + + @Test + void testIsUserLevelRoleUser() { + assertTrue( + UserLevelRoles.isUserLevelRole(Role.ofName("USER")), "USER should be user level role"); + } + + @Test + void testIsUserLevelRoleExternal() { + assertTrue( + UserLevelRoles.isUserLevelRole(Role.ofName("EXTERNAL")), + "EXTERNAL should be user level role"); + } + + @Test + void testIsNotUserLevelRole() { + assertFalse( + UserLevelRoles.isUserLevelRole(Role.ofName("ABC")), "ABC should't be user level role"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundExceptionTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundExceptionTest.java index f88584c..d042fe6 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundExceptionTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/exception/AnchorNotFoundExceptionTest.java @@ -4,20 +4,16 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; +import org.junit.jupiter.api.Test; class AnchorNotFoundExceptionTest { - @Test - void test() { - Anchor anchor = Anchor.ofString("abc"); - AnchorNotFoundException e = new AnchorNotFoundException(anchor); - assertEquals(anchor, e.getAnchor(), "unexpecatd anchor"); - assertThat( - "message should contains 'abc'", - e.getMessage(), - containsString(" abc ")); - } + @Test + void test() { + Anchor anchor = Anchor.ofString("abc"); + AnchorNotFoundException e = new AnchorNotFoundException(anchor); + assertEquals(anchor, e.getAnchor(), "unexpecatd anchor"); + assertThat("message should contains 'abc'", e.getMessage(), containsString(" abc ")); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolverTest.java b/src/test/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolverTest.java index ef8fc01..158ee9e 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolverTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/domain/service/IdentifierResolverTest.java @@ -6,55 +6,55 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.exception.AnchorNotFoundException; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.util.Optional; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class IdentifierResolverTest { - @Test - void testResolveWithId() { + @Test + void testResolveWithId() { - Identifier identifier = Identifier.ofId("123"); - UserRepository repository = mock(); - IdentifierResolver resolver = new IdentifierResolver(repository); + Identifier identifier = Identifier.ofId("123"); + UserRepository repository = mock(); + IdentifierResolver resolver = new IdentifierResolver(repository); - String id = resolver.resolveIdentifier(identifier); + String id = resolver.resolveIdentifier(identifier); - assertEquals("123", id, "unexpected id"); - } + assertEquals("123", id, "unexpected id"); + } - @Test - void testResolveWithAnchor() { + @Test + void testResolveWithAnchor() { - Anchor anchor = Anchor.ofString("abc"); - Identifier identifier = Identifier.ofAnchor(anchor); - UserRepository repository = mock(); - when(repository.resolveAnchor(any())).thenReturn(Optional.of("123")); - IdentifierResolver resolver = new IdentifierResolver(repository); + Anchor anchor = Anchor.ofString("abc"); + Identifier identifier = Identifier.ofAnchor(anchor); + UserRepository repository = mock(); + when(repository.resolveAnchor(any())).thenReturn(Optional.of("123")); + IdentifierResolver resolver = new IdentifierResolver(repository); - String id = resolver.resolveIdentifier(identifier); + String id = resolver.resolveIdentifier(identifier); - assertEquals("123", id, "unexpected id"); - } + assertEquals("123", id, "unexpected id"); + } - @Test - void testResolveWithAnchorNotFound() { + @Test + void testResolveWithAnchorNotFound() { - Anchor anchor = Anchor.ofString("abc"); - Identifier identifier = Identifier.ofAnchor(anchor); - UserRepository repository = mock(); - when(repository.resolveAnchor(any())).thenReturn(Optional.empty()); - IdentifierResolver resolver = new IdentifierResolver(repository); + Anchor anchor = Anchor.ofString("abc"); + Identifier identifier = Identifier.ofAnchor(anchor); + UserRepository repository = mock(); + when(repository.resolveAnchor(any())).thenReturn(Optional.empty()); + IdentifierResolver resolver = new IdentifierResolver(repository); - assertThrows(AnchorNotFoundException.class, () -> { - resolver.resolveIdentifier(identifier); - }); - } + assertThrows( + AnchorNotFoundException.class, + () -> { + resolver.resolveIdentifier(identifier); + }); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByTokenTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByTokenTest.java index 5a2bc94..bc359c2 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByTokenTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/AuthenticateByTokenTest.java @@ -8,11 +8,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.time.OffsetDateTime; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.AccessToken; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessTokenExpiredException; @@ -21,187 +16,156 @@ import com.sitepark.ies.userrepository.core.domain.exception.InvalidAccessTokenException; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.time.OffsetDateTime; +import java.util.Optional; +import org.junit.jupiter.api.Test; class AuthenticateByTokenTest { - private static final String TOKEN_NAME = "Test Token"; - - private static final String TOKEN_STRING = "abc"; - - @Test - void testTokenNotFound() { - - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.empty()); - UserRepository userRepository = mock(); + private static final String TOKEN_NAME = "Test Token"; + + private static final String TOKEN_STRING = "abc"; + + @Test + void testTokenNotFound() { - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.empty()); + UserRepository userRepository = mock(); - assertThrows(InvalidAccessTokenException.class, () -> { - authenticateByToken.authenticateByToken(TOKEN_STRING); - }); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @Test - void testTokenNotActive() { + assertThrows( + InvalidAccessTokenException.class, + () -> { + authenticateByToken.authenticateByToken(TOKEN_STRING); + }); + } - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .user("2") - .active(false) - .build(); + @Test + void testTokenNotActive() { - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - UserRepository userRepository = mock(); + AccessToken accessToken = + AccessToken.builder().id("1").name(TOKEN_NAME).user("2").active(false).build(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + UserRepository userRepository = mock(); - assertThrows(AccessTokenNotActiveException.class, () -> { - authenticateByToken.authenticateByToken(TOKEN_STRING); - }); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @Test - void testTokenRevoked() { + assertThrows( + AccessTokenNotActiveException.class, + () -> { + authenticateByToken.authenticateByToken(TOKEN_STRING); + }); + } - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .user("2") - .revoked(true) - .build(); + @Test + void testTokenRevoked() { - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - UserRepository userRepository = mock(); + AccessToken accessToken = + AccessToken.builder().id("1").name(TOKEN_NAME).user("2").revoked(true).build(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + UserRepository userRepository = mock(); - assertThrows(AccessTokenRevokedException.class, () -> { - authenticateByToken.authenticateByToken("abc"); - }); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - @Test - void testTokenExpired() { + assertThrows( + AccessTokenRevokedException.class, + () -> { + authenticateByToken.authenticateByToken("abc"); + }); + } - OffsetDateTime expiredAt = OffsetDateTime.now().minusDays(1); + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + @Test + void testTokenExpired() { - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .user("2") - .expiresAt(expiredAt) - .build(); + OffsetDateTime expiredAt = OffsetDateTime.now().minusDays(1); - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - UserRepository userRepository = mock(); + AccessToken accessToken = + AccessToken.builder().id("1").name(TOKEN_NAME).user("2").expiresAt(expiredAt).build(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + UserRepository userRepository = mock(); - AccessTokenExpiredException e = assertThrows(AccessTokenExpiredException.class, () -> { - authenticateByToken.authenticateByToken(TOKEN_STRING); - }); - assertNotNull(e.getExpiredAt(), "expiredAt expected"); - assertNotNull(e.getMessage(), "message expected"); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @Test - void testUserNotFound() { + AccessTokenExpiredException e = + assertThrows( + AccessTokenExpiredException.class, + () -> { + authenticateByToken.authenticateByToken(TOKEN_STRING); + }); + assertNotNull(e.getExpiredAt(), "expiredAt expected"); + assertNotNull(e.getMessage(), "message expected"); + } - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .user("2") - .build(); + @Test + void testUserNotFound() { - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + AccessToken accessToken = AccessToken.builder().id("1").name(TOKEN_NAME).user("2").build(); - UserRepository userRepository = mock(); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - when(userRepository.get(anyString())).thenReturn(Optional.empty()); + UserRepository userRepository = mock(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + when(userRepository.get(anyString())).thenReturn(Optional.empty()); - assertThrows(InvalidAccessTokenException.class, () -> { - authenticateByToken.authenticateByToken(TOKEN_STRING); - }); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @Test - void testValidAutentification() { + assertThrows( + InvalidAccessTokenException.class, + () -> { + authenticateByToken.authenticateByToken(TOKEN_STRING); + }); + } - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .user("2") - .build(); + @Test + void testValidAutentification() { - User user = User.builder() - .id("1") - .login("test") - .build(); + AccessToken accessToken = AccessToken.builder().id("1").name(TOKEN_NAME).user("2").build(); - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + User user = User.builder().id("1").login("test").build(); - UserRepository userRepository = mock(); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - when(userRepository.get(anyString())).thenReturn(Optional.of(user)); + UserRepository userRepository = mock(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + when(userRepository.get(anyString())).thenReturn(Optional.of(user)); - User authenticatedUser = authenticateByToken.authenticateByToken(TOKEN_STRING); - assertEquals(user.getId().get(), authenticatedUser.getId().get(), "unexpected user"); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); - @Test - void testValidAutentificationWithExpiredDate() { + User authenticatedUser = authenticateByToken.authenticateByToken(TOKEN_STRING); + assertEquals(user.getId().get(), authenticatedUser.getId().get(), "unexpected user"); + } - OffsetDateTime expiredAt = OffsetDateTime.now().plusDays(1); + @Test + void testValidAutentificationWithExpiredDate() { - AccessToken accessToken = AccessToken.builder() - .id("1") - .name(TOKEN_NAME) - .expiresAt(expiredAt) - .user("2") - .build(); + OffsetDateTime expiredAt = OffsetDateTime.now().plusDays(1); - User user = User.builder() - .id("1") - .login("test") - .build(); + AccessToken accessToken = + AccessToken.builder().id("1").name(TOKEN_NAME).expiresAt(expiredAt).user("2").build(); - AccessTokenRepository accessTokenRepository = mock(); - when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); + User user = User.builder().id("1").login("test").build(); - UserRepository userRepository = mock(); + AccessTokenRepository accessTokenRepository = mock(); + when(accessTokenRepository.getByToken(any())).thenReturn(Optional.of(accessToken)); - when(userRepository.get(anyString())).thenReturn(Optional.of(user)); + UserRepository userRepository = mock(); - var authenticateByToken = new AuthenticateByToken( - accessTokenRepository, - userRepository); + when(userRepository.get(anyString())).thenReturn(Optional.of(user)); - User authenticatedUser = authenticateByToken.authenticateByToken(TOKEN_STRING); - assertEquals(user.getId().get(), authenticatedUser.getId().get(), "unexpected user"); - } + var authenticateByToken = new AuthenticateByToken(accessTokenRepository, userRepository); + User authenticatedUser = authenticateByToken.authenticateByToken(TOKEN_STRING); + assertEquals(user.getId().get(), authenticatedUser.getId().get(), "unexpected user"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationTokenTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationTokenTest.java index 057fd2e..c548ac2 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationTokenTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateImpersonationTokenTest.java @@ -7,10 +7,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.AccessToken; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; @@ -18,72 +14,71 @@ import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.util.Optional; +import org.junit.jupiter.api.Test; class CreateImpersonationTokenTest { - @Test - void testAccessDenied() { - - AccessTokenRepository accessTokenRepository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isImpersonationTokensManageable()).thenReturn(false); - UserRepository userRepository = mock(UserRepository.class); + @Test + void testAccessDenied() { - AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); + AccessTokenRepository accessTokenRepository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isImpersonationTokensManageable()).thenReturn(false); + UserRepository userRepository = mock(UserRepository.class); - var createImpersonationToken = new CreateImpersonationToken( - accessTokenRepository, - accessControl, - userRepository); + AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); - assertThrows(AccessDeniedException.class, () -> { - createImpersonationToken.createPersonalAccessToken(accessToken); - }); + var createImpersonationToken = + new CreateImpersonationToken(accessTokenRepository, accessControl, userRepository); - verify(accessControl).isImpersonationTokensManageable(); - } + assertThrows( + AccessDeniedException.class, + () -> { + createImpersonationToken.createPersonalAccessToken(accessToken); + }); - @Test - void testUserNotFound() { + verify(accessControl).isImpersonationTokensManageable(); + } - AccessTokenRepository accessTokenRepository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isImpersonationTokensManageable()).thenReturn(true); - UserRepository userRepository = mock(UserRepository.class); - when(userRepository.get(anyString())).thenReturn(Optional.empty()); + @Test + void testUserNotFound() { - AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); + AccessTokenRepository accessTokenRepository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isImpersonationTokensManageable()).thenReturn(true); + UserRepository userRepository = mock(UserRepository.class); + when(userRepository.get(anyString())).thenReturn(Optional.empty()); - var createImpersonationToken = new CreateImpersonationToken( - accessTokenRepository, - accessControl, - userRepository); + AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); - assertThrows(UserNotFoundException.class, () -> { - createImpersonationToken.createPersonalAccessToken(accessToken); - }); - } + var createImpersonationToken = + new CreateImpersonationToken(accessTokenRepository, accessControl, userRepository); - @Test - void testCreate() { + assertThrows( + UserNotFoundException.class, + () -> { + createImpersonationToken.createPersonalAccessToken(accessToken); + }); + } - AccessTokenRepository accessTokenRepository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isImpersonationTokensManageable()).thenReturn(true); - UserRepository userRepository = mock(UserRepository.class); - User user = mock(User.class); - when(userRepository.get(anyString())).thenReturn(Optional.of(user)); + @Test + void testCreate() { - AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); + AccessTokenRepository accessTokenRepository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isImpersonationTokensManageable()).thenReturn(true); + UserRepository userRepository = mock(UserRepository.class); + User user = mock(User.class); + when(userRepository.get(anyString())).thenReturn(Optional.of(user)); - var createImpersonationToken = new CreateImpersonationToken( - accessTokenRepository, - accessControl, - userRepository); + AccessToken accessToken = AccessToken.builder().user("123").name("Test Token").build(); - createImpersonationToken.createPersonalAccessToken(accessToken); + var createImpersonationToken = + new CreateImpersonationToken(accessTokenRepository, accessControl, userRepository); - verify(accessTokenRepository).create(any()); - } + createImpersonationToken.createPersonalAccessToken(accessToken); + verify(accessTokenRepository).create(any()); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateUserTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateUserTest.java index 850f0db..0ba6ccd 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateUserTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/CreateUserTest.java @@ -10,11 +10,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.util.Arrays; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.entity.role.Ref; @@ -27,195 +22,162 @@ import com.sitepark.ies.userrepository.core.port.IdGenerator; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.util.Arrays; +import java.util.Optional; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class CreateUserTest { - @Test - void testAccessDeniedCreate() { - - UserRepository repository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserCreateable()).thenReturn(false); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - - User user = User.builder() - .login("test") - .build(); - - var createUserUseCase = new CreateUser( - repository, - null, - accessControl, - null, - extensionsNotifier); - assertThrows(AccessDeniedException.class, () -> { - createUserUseCase.createUser(user); - }); - - verify(accessControl).isUserCreateable(); - } - - @Test - void testWithId() { - - User user = User.builder() - .id("123") - .login("test") - .build(); - - var createUserUseCase = new CreateUser( - null, - null, - null, - null, - null); - assertThrows(IllegalArgumentException.class, () -> { - createUserUseCase.createUser(user); - }); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testAnchorAlreadyExists() { - - UserRepository repository = mock(); - when(repository.resolveAnchor(Anchor.ofString("test.user"))) - .thenReturn(Optional.of("123")); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserCreateable()).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - - User user = User.builder() - .anchor("test.user") - .login("test") - .build(); - - var createUserUseCase = new CreateUser( - repository, - null, - accessControl, - null, - extensionsNotifier); - - AnchorAlreadyExistsException e = assertThrows(AnchorAlreadyExistsException.class, () -> { - createUserUseCase.createUser(user); - }); - - assertEquals(Anchor.ofString("test.user"), e.getAnchor(), "unexpected anchor"); - assertEquals("123", e.getOwner(), "unexpected owner"); - assertNotNull(e.getMessage(), "message is null"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testCreateWithRoles() { - - AccessControl accessControl = mock(); - when(accessControl.isUserCreateable()).thenReturn(true); - IdGenerator idGenerator = mock(); - when(idGenerator.generate()).thenReturn("123"); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveLogin(anyString())).thenReturn(Optional.empty()); - RoleAssigner roleAssigner = mock(); - - User user = User.builder() - .login("test") - .roleList(UserLevelRoles.USER, Ref.ofId("333")) - .build(); - - var createUserUseCase = new CreateUser( - repository, - roleAssigner, - accessControl, - idGenerator, - extensionsNotifier); - - createUserUseCase.createUser(user); - - User effectiveUser = User.builder() - .id("123") - .login("test") - .roleList(UserLevelRoles.USER, Ref.ofId("333")) - .build(); - - verify(repository).create(eq(effectiveUser)); - verify(roleAssigner).assignRoleToUser( - Arrays.asList(UserLevelRoles.USER, Ref.ofId("333")), - Arrays.asList("123")); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testCreateWithAnchor() { - - AccessControl accessControl = mock(); - when(accessControl.isUserCreateable()).thenReturn(true); - IdGenerator idGenerator = mock(); - when(idGenerator.generate()).thenReturn("123"); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveAnchor(any())).thenReturn(Optional.empty()); - when(repository.resolveLogin(anyString())).thenReturn(Optional.empty()); - RoleAssigner roleAssigner = mock(); - - User user = User.builder() - .anchor("test.anchor") - .login("test") - .build(); - - var createUserUseCase = new CreateUser( - repository, - roleAssigner, - accessControl, - idGenerator, - extensionsNotifier); - - createUserUseCase.createUser(user); - - User effectiveUser = User.builder() - .id("123") - .anchor("test.anchor") - .login("test") - .build(); - - verify(repository).create(eq(effectiveUser)); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testCreateWithExistsLogin() { - - AccessControl accessControl = mock(); - when(accessControl.isUserCreateable()).thenReturn(true); - IdGenerator idGenerator = mock(); - when(idGenerator.generate()).thenReturn("123"); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveLogin(anyString())).thenReturn(Optional.of("345")); - RoleAssigner roleAssigner = mock(); - - User user = User.builder() - .login("test") - .roleList(UserLevelRoles.USER, Ref.ofId("333")) - .build(); - - var createUserUseCase = new CreateUser( - repository, - roleAssigner, - accessControl, - idGenerator, - extensionsNotifier); - - LoginAlreadyExistsException e = assertThrows(LoginAlreadyExistsException.class, () -> { - createUserUseCase.createUser(user); - }); - assertEquals("test", e.getLogin(), "unexpected login"); - assertEquals("345", e.getOwner(), "unexpected owner"); - assertNotNull(e.getMessage(), "message is null"); - } + @Test + void testAccessDeniedCreate() { + + UserRepository repository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserCreateable()).thenReturn(false); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + + User user = User.builder().login("test").build(); + + var createUserUseCase = + new CreateUser(repository, null, accessControl, null, extensionsNotifier); + assertThrows( + AccessDeniedException.class, + () -> { + createUserUseCase.createUser(user); + }); + + verify(accessControl).isUserCreateable(); + } + + @Test + void testWithId() { + + User user = User.builder().id("123").login("test").build(); + + var createUserUseCase = new CreateUser(null, null, null, null, null); + assertThrows( + IllegalArgumentException.class, + () -> { + createUserUseCase.createUser(user); + }); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testAnchorAlreadyExists() { + + UserRepository repository = mock(); + when(repository.resolveAnchor(Anchor.ofString("test.user"))).thenReturn(Optional.of("123")); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserCreateable()).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + + User user = User.builder().anchor("test.user").login("test").build(); + + var createUserUseCase = + new CreateUser(repository, null, accessControl, null, extensionsNotifier); + + AnchorAlreadyExistsException e = + assertThrows( + AnchorAlreadyExistsException.class, + () -> { + createUserUseCase.createUser(user); + }); + + assertEquals(Anchor.ofString("test.user"), e.getAnchor(), "unexpected anchor"); + assertEquals("123", e.getOwner(), "unexpected owner"); + assertNotNull(e.getMessage(), "message is null"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testCreateWithRoles() { + + AccessControl accessControl = mock(); + when(accessControl.isUserCreateable()).thenReturn(true); + IdGenerator idGenerator = mock(); + when(idGenerator.generate()).thenReturn("123"); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveLogin(anyString())).thenReturn(Optional.empty()); + RoleAssigner roleAssigner = mock(); + + User user = User.builder().login("test").roleList(UserLevelRoles.USER, Ref.ofId("333")).build(); + + var createUserUseCase = + new CreateUser(repository, roleAssigner, accessControl, idGenerator, extensionsNotifier); + + createUserUseCase.createUser(user); + + User effectiveUser = + User.builder() + .id("123") + .login("test") + .roleList(UserLevelRoles.USER, Ref.ofId("333")) + .build(); + + verify(repository).create(eq(effectiveUser)); + verify(roleAssigner) + .assignRoleToUser( + Arrays.asList(UserLevelRoles.USER, Ref.ofId("333")), Arrays.asList("123")); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testCreateWithAnchor() { + + AccessControl accessControl = mock(); + when(accessControl.isUserCreateable()).thenReturn(true); + IdGenerator idGenerator = mock(); + when(idGenerator.generate()).thenReturn("123"); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveAnchor(any())).thenReturn(Optional.empty()); + when(repository.resolveLogin(anyString())).thenReturn(Optional.empty()); + RoleAssigner roleAssigner = mock(); + + User user = User.builder().anchor("test.anchor").login("test").build(); + + var createUserUseCase = + new CreateUser(repository, roleAssigner, accessControl, idGenerator, extensionsNotifier); + + createUserUseCase.createUser(user); + + User effectiveUser = User.builder().id("123").anchor("test.anchor").login("test").build(); + + verify(repository).create(eq(effectiveUser)); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testCreateWithExistsLogin() { + + AccessControl accessControl = mock(); + when(accessControl.isUserCreateable()).thenReturn(true); + IdGenerator idGenerator = mock(); + when(idGenerator.generate()).thenReturn("123"); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveLogin(anyString())).thenReturn(Optional.of("345")); + RoleAssigner roleAssigner = mock(); + + User user = User.builder().login("test").roleList(UserLevelRoles.USER, Ref.ofId("333")).build(); + + var createUserUseCase = + new CreateUser(repository, roleAssigner, accessControl, idGenerator, extensionsNotifier); + + LoginAlreadyExistsException e = + assertThrows( + LoginAlreadyExistsException.class, + () -> { + createUserUseCase.createUser(user); + }); + assertEquals("test", e.getLogin(), "unexpected login"); + assertEquals("345", e.getOwner(), "unexpected owner"); + assertNotNull(e.getMessage(), "message is null"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/GetUserTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/GetUserTest.java index ac2441d..314f243 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/GetUserTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/GetUserTest.java @@ -8,11 +8,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.Arrays; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.entity.role.Ref; @@ -23,109 +18,103 @@ import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.util.Arrays; +import java.util.Optional; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class GetUserTest { - @Test - void testAccessDeniedGetWithId() { - - UserRepository userRepository = mock(); - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - RoleAssigner roleAssigner = mock(); - AccessControl accessControl = mock(); - when(accessControl.isUserReadable("123")).thenReturn(false); - - GetUser getUserUseCase = new GetUser( - userRepository, - identifierResolver, - roleAssigner, - accessControl); - - assertThrows(AccessDeniedException.class, () -> { - getUserUseCase.getUser(Identifier.ofString("123")); - }); - } - - @Test - void testAccessDeniedGetWithAnchor() { - - UserRepository userRepository = mock(); - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - RoleAssigner roleAssigner = mock(); - AccessControl accessControl = mock(); - when(accessControl.isUserReadable("123")).thenReturn(false); - - GetUser getUserUseCase = new GetUser( - userRepository, - identifierResolver, - roleAssigner, - accessControl); - - assertThrows(AccessDeniedException.class, () -> { - getUserUseCase.getUser(Identifier.ofString("abc")); - }); - } - - @Test - void testGet() { - - UserRepository userRepository = mock(); - User storedUser = User.builder() - .id("123") - .login("test") - .build(); - when(userRepository.get("123")).thenReturn(Optional.of(storedUser)); - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - RoleAssigner roleAssigner = mock(); - when(roleAssigner.getRolesAssignByUser("123")).thenReturn(Arrays.asList( - UserLevelRoles.USER, - Ref.ofAnchor("role.a") - )); - AccessControl accessControl = mock(); - when(accessControl.isUserReadable(anyString())).thenReturn(true); - - GetUser getUserUseCase = new GetUser( - userRepository, - identifierResolver, - roleAssigner, - accessControl); - - User expectedUser = User.builder() - .id("123") - .login("test") - .roleList(UserLevelRoles.USER, Ref.ofAnchor("role.a")) - .build(); - - User user = getUserUseCase.getUser(Identifier.ofString("123")); - - assertEquals(expectedUser, user, "unexpected user"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testGetUserNotFound() { - - UserRepository userRepository = mock(); - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - RoleAssigner roleAssigner = mock(); - AccessControl accessControl = mock(); - when(accessControl.isUserReadable(anyString())).thenReturn(true); - - GetUser getUserUseCase = new GetUser( - userRepository, - identifierResolver, - roleAssigner, - accessControl); - - UserNotFoundException e = assertThrows(UserNotFoundException.class, () -> { - getUserUseCase.getUser(Identifier.ofString("123")); - }); - assertEquals("123", e.getId(), "unexpected user"); - assertNotNull(e.getMessage(), "message is null"); - } + @Test + void testAccessDeniedGetWithId() { + + UserRepository userRepository = mock(); + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + RoleAssigner roleAssigner = mock(); + AccessControl accessControl = mock(); + when(accessControl.isUserReadable("123")).thenReturn(false); + + GetUser getUserUseCase = + new GetUser(userRepository, identifierResolver, roleAssigner, accessControl); + + assertThrows( + AccessDeniedException.class, + () -> { + getUserUseCase.getUser(Identifier.ofString("123")); + }); + } + + @Test + void testAccessDeniedGetWithAnchor() { + + UserRepository userRepository = mock(); + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + RoleAssigner roleAssigner = mock(); + AccessControl accessControl = mock(); + when(accessControl.isUserReadable("123")).thenReturn(false); + + GetUser getUserUseCase = + new GetUser(userRepository, identifierResolver, roleAssigner, accessControl); + + assertThrows( + AccessDeniedException.class, + () -> { + getUserUseCase.getUser(Identifier.ofString("abc")); + }); + } + + @Test + void testGet() { + + UserRepository userRepository = mock(); + User storedUser = User.builder().id("123").login("test").build(); + when(userRepository.get("123")).thenReturn(Optional.of(storedUser)); + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + RoleAssigner roleAssigner = mock(); + when(roleAssigner.getRolesAssignByUser("123")) + .thenReturn(Arrays.asList(UserLevelRoles.USER, Ref.ofAnchor("role.a"))); + AccessControl accessControl = mock(); + when(accessControl.isUserReadable(anyString())).thenReturn(true); + + GetUser getUserUseCase = + new GetUser(userRepository, identifierResolver, roleAssigner, accessControl); + + User expectedUser = + User.builder() + .id("123") + .login("test") + .roleList(UserLevelRoles.USER, Ref.ofAnchor("role.a")) + .build(); + + User user = getUserUseCase.getUser(Identifier.ofString("123")); + + assertEquals(expectedUser, user, "unexpected user"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testGetUserNotFound() { + + UserRepository userRepository = mock(); + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + RoleAssigner roleAssigner = mock(); + AccessControl accessControl = mock(); + when(accessControl.isUserReadable(anyString())).thenReturn(true); + + GetUser getUserUseCase = + new GetUser(userRepository, identifierResolver, roleAssigner, accessControl); + + UserNotFoundException e = + assertThrows( + UserNotFoundException.class, + () -> { + getUserUseCase.getUser(Identifier.ofString("123")); + }); + assertEquals("123", e.getId(), "unexpected user"); + assertNotNull(e.getMessage(), "message is null"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/PurgeUserTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/PurgeUserTest.java index ed41276..e5ea701 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/PurgeUserTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/PurgeUserTest.java @@ -7,8 +7,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Identifier; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.domain.service.IdentifierResolver; @@ -16,52 +14,53 @@ import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; import com.sitepark.ies.userrepository.core.port.ExtensionsNotifier; import com.sitepark.ies.userrepository.core.port.UserRepository; +import org.junit.jupiter.api.Test; class PurgeUserTest { - @Test - void testAccessDenied() { + @Test + void testAccessDenied() { - AccessControl accessControl = mock(AccessControl.class); - IdentifierResolver identifierResolver = mock(); - AccessTokenRepository accessTokenRepository = mock(AccessTokenRepository.class); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - when(accessControl.isUserRemovable(anyString())).thenReturn(false); + AccessControl accessControl = mock(AccessControl.class); + IdentifierResolver identifierResolver = mock(); + AccessTokenRepository accessTokenRepository = mock(AccessTokenRepository.class); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + when(accessControl.isUserRemovable(anyString())).thenReturn(false); - var purgeEntity = new PurgeUser( - null, - identifierResolver, - extensionsNotifier, - accessControl, - accessTokenRepository); - assertThrows(AccessDeniedException.class, () -> { - purgeEntity.purgeUser(Identifier.ofId("10")); - }); - } + var purgeEntity = + new PurgeUser( + null, identifierResolver, extensionsNotifier, accessControl, accessTokenRepository); + assertThrows( + AccessDeniedException.class, + () -> { + purgeEntity.purgeUser(Identifier.ofId("10")); + }); + } - @SuppressWarnings("PMD") - @Test - void testPurge() { + @SuppressWarnings("PMD") + @Test + void testPurge() { - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("10"); - AccessControl accessControl = mock(AccessControl.class); - AccessTokenRepository accessTokenRepository = mock(AccessTokenRepository.class); - when(accessControl.isUserRemovable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("10"); + AccessControl accessControl = mock(AccessControl.class); + AccessTokenRepository accessTokenRepository = mock(AccessTokenRepository.class); + when(accessControl.isUserRemovable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - UserRepository repository = mock(UserRepository.class); + UserRepository repository = mock(UserRepository.class); - PurgeUser purgeEntity = new PurgeUser( - repository, - identifierResolver, - extensionsNotifier, - accessControl, - accessTokenRepository); - purgeEntity.purgeUser(Identifier.ofId("10")); + PurgeUser purgeEntity = + new PurgeUser( + repository, + identifierResolver, + extensionsNotifier, + accessControl, + accessTokenRepository); + purgeEntity.purgeUser(Identifier.ofId("10")); - verify(repository).remove("10"); - verify(extensionsNotifier).notifyPurge("10"); - verify(accessTokenRepository).purgeByUser("10"); - } + verify(repository).remove("10"); + verify(extensionsNotifier).notifyPurge("10"); + verify(accessTokenRepository).purgeByUser("10"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationTokenTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationTokenTest.java index f57af36..0016de3 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationTokenTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/RevokeImpersonationTokenTest.java @@ -5,49 +5,44 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; import com.sitepark.ies.userrepository.core.port.AccessControl; import com.sitepark.ies.userrepository.core.port.AccessTokenRepository; +import org.junit.jupiter.api.Test; class RevokeImpersonationTokenTest { - @Test - void testAccessDenied() { - - AccessTokenRepository accessTokenRepository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isImpersonationTokensManageable()).thenReturn(false); - - var revokeImpersonationToken = new RevokeImpersonationToken( - accessTokenRepository, - accessControl); - - assertThrows(AccessDeniedException.class, () -> { - revokeImpersonationToken.revokeImpersonationToken("1", "2"); - }); - - verify(accessControl).isImpersonationTokensManageable(); - } + @Test + void testAccessDenied() { - @Test - void testRevoke() { + AccessTokenRepository accessTokenRepository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isImpersonationTokensManageable()).thenReturn(false); - AccessTokenRepository accessTokenRepository = mock(); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isImpersonationTokensManageable()).thenReturn(true); + var revokeImpersonationToken = + new RevokeImpersonationToken(accessTokenRepository, accessControl); - var revokeImpersonationToken = new RevokeImpersonationToken( - accessTokenRepository, - accessControl); + assertThrows( + AccessDeniedException.class, + () -> { + revokeImpersonationToken.revokeImpersonationToken("1", "2"); + }); - revokeImpersonationToken.revokeImpersonationToken("1", "2"); + verify(accessControl).isImpersonationTokensManageable(); + } - verify(accessTokenRepository).revoke("1", "2"); - } + @Test + void testRevoke() { + AccessTokenRepository accessTokenRepository = mock(); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isImpersonationTokensManageable()).thenReturn(true); + var revokeImpersonationToken = + new RevokeImpersonationToken(accessTokenRepository, accessControl); + revokeImpersonationToken.revokeImpersonationToken("1", "2"); + verify(accessTokenRepository).revoke("1", "2"); + } } diff --git a/src/test/java/com/sitepark/ies/userrepository/core/usecase/UpdateUserTest.java b/src/test/java/com/sitepark/ies/userrepository/core/usecase/UpdateUserTest.java index 60a3270..8edec39 100644 --- a/src/test/java/com/sitepark/ies/userrepository/core/usecase/UpdateUserTest.java +++ b/src/test/java/com/sitepark/ies/userrepository/core/usecase/UpdateUserTest.java @@ -10,10 +10,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.ies.userrepository.core.domain.entity.Anchor; import com.sitepark.ies.userrepository.core.domain.entity.User; import com.sitepark.ies.userrepository.core.domain.exception.AccessDeniedException; @@ -25,399 +21,305 @@ import com.sitepark.ies.userrepository.core.port.ExtensionsNotifier; import com.sitepark.ies.userrepository.core.port.RoleAssigner; import com.sitepark.ies.userrepository.core.port.UserRepository; +import java.util.Optional; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class UpdateUserTest { - @Test - void testAccessDeniedUpdate() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserWritable(anyString())).thenReturn(false); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - - User user = User.builder() - .id("123") - .login("test") - .build(); - - var updateUserUseCase = new UpdateUser( - null, - identifierResolver, - null, - accessControl, - extensionsNotifier); - assertThrows(AccessDeniedException.class, () -> { - updateUserUseCase.updateUser(user); - }); - - verify(accessControl).isUserWritable("123"); - } - - @Test - void testWithoutAnchorAndId() { - - User user = User.builder() - .login("test") - .build(); - - var updateUserUseCase = new UpdateUser( - null, - null, - null, - null, - null); - assertThrows(IllegalArgumentException.class, () -> { - updateUserUseCase.updateUser(user); - }); - } - - - @Test - void testUpdateUserNotFound() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - - UserRepository repository = mock(UserRepository.class); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - null, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .anchor("user.test") - .login("test") - .build(); - - UserNotFoundException thrown = assertThrows(UserNotFoundException.class, () -> { - updateUserUseCase.updateUser(user); - }); - - assertEquals("123", thrown.getId(), "unexpected id"); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testChangeLoginToAlreadyExistsLogin() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - RoleAssigner roleAssigner = mock(); - - UserRepository repository = mock(UserRepository.class); - when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); - when(repository.resolveLogin("test2")).thenReturn(Optional.of("55")); - - User storedUser = User.builder() - .id("123") - .anchor("user.test") - .login("test") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .anchor("user.test") - .login("test2") - .build(); - - LoginAlreadyExistsException thrown = assertThrows(LoginAlreadyExistsException.class, () -> { - updateUserUseCase.updateUser(user); - }); - - assertEquals("55", thrown.getOwner(), "unexpected owner"); - assertEquals("test2", thrown.getLogin(), "unexpected login"); - } - - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testUpdateUnchanged() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - RoleAssigner roleAssigner = mock(); - - UserRepository repository = mock(UserRepository.class); - when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); - - User storedUser = User.builder() - .id("123") - .anchor("user.test") - .login("test") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .anchor("user.test") - .login("test") - .build(); - - updateUserUseCase.updateUser(user); - - verify(repository).get(anyString()); - verify(repository).resolveLogin(anyString()); - - verifyNoMoreInteractions(repository); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testUpdateViaIdWithStoredAnchor() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(AccessControl.class); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); - RoleAssigner roleAssigner = mock(); - - UserRepository repository = mock(UserRepository.class); - when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); - - User storedUser = User.builder() - .id("123") - .anchor("user.test") - .login("test") - .lastname("A") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .login("test") - .lastname("B") - .build(); - - updateUserUseCase.updateUser(user); - - User effectiveUser = User.builder() - .id("123") - .login("test") - .anchor("user.test") - .lastname("B") - .build(); - - verify(repository).get(anyString()); - verify(repository).resolveLogin(anyString()); - verify(repository).update(effectiveUser); - - verifyNoMoreInteractions(repository); - } - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testViaAnchor() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); - when(repository.resolveAnchor(Anchor.ofString("user.test"))).thenReturn(Optional.of("123")); - RoleAssigner roleAssigner = mock(); - - User storedUser = User.builder() - .id("123") - .login("test") - .anchor("user.test") - .lastname("A") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .login("test") - .anchor("user.test") - .lastname("B") - .build(); - - updateUserUseCase.updateUser(user); - - User effectiveUser = User.builder() - .id("123") - .login("test") - .anchor("user.test") - .lastname("B") - .build(); - - verify(repository).get(anyString()); - verify(identifierResolver).resolveIdentifier(any()); - verify(repository).resolveLogin(anyString()); - verify(repository).update(eq(effectiveUser)); - verify(extensionsNotifier).notifyUpdated(any()); - verifyNoMoreInteractions(repository); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testUpdateAnchor() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); - RoleAssigner roleAssigner = mock(); - - User storedUser = User.builder() - .id("123") - .login("test") - .anchor("user.test") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .login("test") - .anchor("user.test2") - .build(); - - updateUserUseCase.updateUser(user); - - User effectiveUser = User.builder() - .id("123") - .login("test") - .anchor("user.test2") - .build(); - - verify(repository).get(anyString()); - verify(repository).resolveLogin(anyString()); - verify(repository).update(eq(effectiveUser)); - verify(extensionsNotifier).notifyUpdated(any()); - verifyNoMoreInteractions(repository); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testUpdateLogin() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); - AccessControl accessControl = mock(); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveLogin("test")).thenReturn(Optional.of("55")); - when(repository.resolveLogin("test2")).thenReturn(Optional.empty()); - RoleAssigner roleAssigner = mock(); - - User storedUser = User.builder() - .id("123") - .login("test") - .build(); - when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .id("123") - .login("test2") - .build(); - - updateUserUseCase.updateUser(user); - - User effectiveUser = User.builder() - .id("123") - .login("test2") - .build(); - - verify(repository).get(anyString()); - verify(repository).resolveLogin(anyString()); - verify(repository).update(eq(effectiveUser)); - verify(extensionsNotifier).notifyUpdated(any()); - verifyNoMoreInteractions(repository); - } - - @Test - void testUpdateAnchorNotFound() { - - IdentifierResolver identifierResolver = mock(); - when(identifierResolver.resolveIdentifier(any())).thenThrow(AnchorNotFoundException.class); - AccessControl accessControl = mock(); - when(accessControl.isUserWritable(anyString())).thenReturn(true); - ExtensionsNotifier extensionsNotifier = mock(); - - UserRepository repository = mock(); - when(repository.resolveAnchor(Anchor.ofString("user.test"))).thenReturn(Optional.empty()); - RoleAssigner roleAssigner = mock(); - - var updateUserUseCase = new UpdateUser( - repository, - identifierResolver, - roleAssigner, - accessControl, - extensionsNotifier); - - User user = User.builder() - .login("test") - .anchor("user.test2") - .build(); - - assertThrows(AnchorNotFoundException.class, () -> { - updateUserUseCase.updateUser(user); - }); - } + @Test + void testAccessDeniedUpdate() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserWritable(anyString())).thenReturn(false); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + + User user = User.builder().id("123").login("test").build(); + + var updateUserUseCase = + new UpdateUser(null, identifierResolver, null, accessControl, extensionsNotifier); + assertThrows( + AccessDeniedException.class, + () -> { + updateUserUseCase.updateUser(user); + }); + + verify(accessControl).isUserWritable("123"); + } + + @Test + void testWithoutAnchorAndId() { + + User user = User.builder().login("test").build(); + + var updateUserUseCase = new UpdateUser(null, null, null, null, null); + assertThrows( + IllegalArgumentException.class, + () -> { + updateUserUseCase.updateUser(user); + }); + } + + @Test + void testUpdateUserNotFound() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + + UserRepository repository = mock(UserRepository.class); + + var updateUserUseCase = + new UpdateUser(repository, identifierResolver, null, accessControl, extensionsNotifier); + + User user = User.builder().id("123").anchor("user.test").login("test").build(); + + UserNotFoundException thrown = + assertThrows( + UserNotFoundException.class, + () -> { + updateUserUseCase.updateUser(user); + }); + + assertEquals("123", thrown.getId(), "unexpected id"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testChangeLoginToAlreadyExistsLogin() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + RoleAssigner roleAssigner = mock(); + + UserRepository repository = mock(UserRepository.class); + when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); + when(repository.resolveLogin("test2")).thenReturn(Optional.of("55")); + + User storedUser = User.builder().id("123").anchor("user.test").login("test").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().id("123").anchor("user.test").login("test2").build(); + + LoginAlreadyExistsException thrown = + assertThrows( + LoginAlreadyExistsException.class, + () -> { + updateUserUseCase.updateUser(user); + }); + + assertEquals("55", thrown.getOwner(), "unexpected owner"); + assertEquals("test2", thrown.getLogin(), "unexpected login"); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testUpdateUnchanged() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + RoleAssigner roleAssigner = mock(); + + UserRepository repository = mock(UserRepository.class); + when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); + + User storedUser = User.builder().id("123").anchor("user.test").login("test").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().id("123").anchor("user.test").login("test").build(); + + updateUserUseCase.updateUser(user); + + verify(repository).get(anyString()); + verify(repository).resolveLogin(anyString()); + + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testUpdateViaIdWithStoredAnchor() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(AccessControl.class); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(ExtensionsNotifier.class); + RoleAssigner roleAssigner = mock(); + + UserRepository repository = mock(UserRepository.class); + when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); + + User storedUser = + User.builder().id("123").anchor("user.test").login("test").lastname("A").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().id("123").login("test").lastname("B").build(); + + updateUserUseCase.updateUser(user); + + User effectiveUser = + User.builder().id("123").login("test").anchor("user.test").lastname("B").build(); + + verify(repository).get(anyString()); + verify(repository).resolveLogin(anyString()); + verify(repository).update(effectiveUser); + + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testViaAnchor() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); + when(repository.resolveAnchor(Anchor.ofString("user.test"))).thenReturn(Optional.of("123")); + RoleAssigner roleAssigner = mock(); + + User storedUser = + User.builder().id("123").login("test").anchor("user.test").lastname("A").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().login("test").anchor("user.test").lastname("B").build(); + + updateUserUseCase.updateUser(user); + + User effectiveUser = + User.builder().id("123").login("test").anchor("user.test").lastname("B").build(); + + verify(repository).get(anyString()); + verify(identifierResolver).resolveIdentifier(any()); + verify(repository).resolveLogin(anyString()); + verify(repository).update(eq(effectiveUser)); + verify(extensionsNotifier).notifyUpdated(any()); + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testUpdateAnchor() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveLogin("test")).thenReturn(Optional.of("123")); + RoleAssigner roleAssigner = mock(); + + User storedUser = User.builder().id("123").login("test").anchor("user.test").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().id("123").login("test").anchor("user.test2").build(); + + updateUserUseCase.updateUser(user); + + User effectiveUser = User.builder().id("123").login("test").anchor("user.test2").build(); + + verify(repository).get(anyString()); + verify(repository).resolveLogin(anyString()); + verify(repository).update(eq(effectiveUser)); + verify(extensionsNotifier).notifyUpdated(any()); + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testUpdateLogin() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenReturn("123"); + AccessControl accessControl = mock(); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveLogin("test")).thenReturn(Optional.of("55")); + when(repository.resolveLogin("test2")).thenReturn(Optional.empty()); + RoleAssigner roleAssigner = mock(); + + User storedUser = User.builder().id("123").login("test").build(); + when(repository.get(anyString())).thenReturn(Optional.of(storedUser)); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().id("123").login("test2").build(); + + updateUserUseCase.updateUser(user); + + User effectiveUser = User.builder().id("123").login("test2").build(); + + verify(repository).get(anyString()); + verify(repository).resolveLogin(anyString()); + verify(repository).update(eq(effectiveUser)); + verify(extensionsNotifier).notifyUpdated(any()); + verifyNoMoreInteractions(repository); + } + + @Test + void testUpdateAnchorNotFound() { + + IdentifierResolver identifierResolver = mock(); + when(identifierResolver.resolveIdentifier(any())).thenThrow(AnchorNotFoundException.class); + AccessControl accessControl = mock(); + when(accessControl.isUserWritable(anyString())).thenReturn(true); + ExtensionsNotifier extensionsNotifier = mock(); + + UserRepository repository = mock(); + when(repository.resolveAnchor(Anchor.ofString("user.test"))).thenReturn(Optional.empty()); + RoleAssigner roleAssigner = mock(); + + var updateUserUseCase = + new UpdateUser( + repository, identifierResolver, roleAssigner, accessControl, extensionsNotifier); + + User user = User.builder().login("test").anchor("user.test2").build(); + + assertThrows( + AnchorNotFoundException.class, + () -> { + updateUserUseCase.updateUser(user); + }); + } }