implement RoleServiceTest

This commit is contained in:
PEDSF 2020-12-05 15:49:53 +01:00
parent 5694967a71
commit bc486de542
38 changed files with 625 additions and 243 deletions

View file

@ -9,13 +9,8 @@ public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBroker
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry message) {
// @formatter:off
// message types other than MESSAGE and SUBSCRIBE
message.simpDestMatchers("/app/**").permitAll()
.simpSubscribeDestMatchers("/topic/**").permitAll()
// catch all
.anyMessage().denyAll();
message.simpDestMatchers("/app/**").permitAll().simpSubscribeDestMatchers("/topic/**").permitAll().anyMessage()
.permitAll();
// @formatter:on
}

View file

@ -20,8 +20,6 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import javax.annotation.Resource;
import java.util.Arrays;
@ -29,7 +27,7 @@ import java.util.List;
import java.util.stream.Collectors;
@Configuration
@EnableWebSecurity(debug = true)
@EnableWebSecurity
@PropertySource("classpath:oauth2.properties")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@ -64,7 +62,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login", "/logout", "/register","/confirm-account").permitAll()
.antMatchers("/websocket/**", "/topic/**", "/app/**").permitAll()
.antMatchers("/webjars/**","/websocket/**", "/topic/**", "/app/**").permitAll()
.antMatchers("/resources/**").permitAll()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/edit/**").authenticated()

View file

@ -3,7 +3,6 @@ package org.springframework.samples.petclinic.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@ -17,17 +16,6 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
/*
* @Override public void registerStompEndpoints(StompEndpointRegistry
* stompEndpointRegistry) {
* stompEndpointRegistry.addEndpoint("/websocket").withSockJS(); }
*
* @Override public void configureMessageBroker(MessageBrokerRegistry registry) {
* registry.enableSimpleBroker("/topic");
* registry.setApplicationDestinationPrefixes("/app"); }
*
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");

View file

@ -80,7 +80,7 @@ class OwnerController extends WebSocketSender {
@GetMapping(CommonEndPoint.OWNERS_FIND)
public String initFindForm(Map<String, Object> model) {
model.put(CommonAttribute.OWNER, new OwnerDTO());
sendSuccessMessage("TEST WEBSOCKET");
return CommonView.OWNER_FIND_OWNERS;
}
@ -105,13 +105,13 @@ class OwnerController extends WebSocketSender {
else if (results.size() == 1) {
// 1 owner found
owner = results.iterator().next();
sendSuccessMessage("TEST WEBSOCKET");
return CommonView.OWNER_OWNERS_R + owner.getId();
}
else {
// multiple owners found
model.put(CommonAttribute.SELECTIONS, results);
sendSuccessMessage("TEST WEBSOCKET");
return CommonView.OWNER_OWNERS_LIST;
}
}
@ -120,7 +120,7 @@ class OwnerController extends WebSocketSender {
public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
OwnerDTO ownerDTO = this.ownerService.findById(ownerId);
model.addAttribute(CommonAttribute.OWNER, ownerDTO);
sendSuccessMessage("TEST WEBSOCKET");
return CommonView.OWNER_CREATE_OR_UPDATE;
}
@ -155,7 +155,7 @@ class OwnerController extends WebSocketSender {
}
modelAndView.addObject(CommonAttribute.OWNER, owner);
sendSuccessMessage("TEST WEBSOCKET");
return modelAndView;
}

View file

@ -42,7 +42,7 @@ import java.util.Collection;
* @author Paul-Emmanuel DOS SANTOS FACAO
*/
@Controller
@RequestMapping("/owners/{ownerId}")
@RequestMapping(CommonEndPoint.OWNERS_ID) // "/owners/{ownerId}")
class PetController extends WebSocketSender {
private final OwnerService ownerService;
@ -62,7 +62,7 @@ class PetController extends WebSocketSender {
@ModelAttribute("owner")
public OwnerDTO findOwner(@PathVariable("ownerId") int ownerId) {
return ownerService.findById(ownerId);
return this.ownerService.findById(ownerId);
}
@InitBinder("owner")
@ -110,14 +110,16 @@ class PetController extends WebSocketSender {
}
}
@GetMapping("/pets/{petId}/edit")
// @GetMapping("/pets/{petId}/edit")
@GetMapping(CommonEndPoint.PETS_ID_EDIT)
public String initUpdateForm(@PathVariable("petId") int petId, ModelMap model) {
PetDTO pet = this.petService.findById(petId);
model.put(CommonAttribute.PET, pet);
return CommonView.PET_CREATE_OR_UPDATE;
}
@PostMapping("/pets/{petId}/edit")
// @PostMapping("/pets/{petId}/edit")
@PostMapping(CommonEndPoint.PETS_ID_EDIT)
public String processUpdateForm(@ModelAttribute("pet") @Valid PetDTO pet, BindingResult result,
@ModelAttribute("owner") OwnerDTO owner, ModelMap model) {
if (result.hasErrors()) {

View file

@ -130,22 +130,4 @@ public class OwnerDTO extends PersonDTO {
.append(CommonAttribute.OWNER_PHONE, this.telephone).toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OwnerDTO))
return false;
OwnerDTO ownerDTO = (OwnerDTO) o;
if (!getAddress().equals(ownerDTO.getAddress()))
return false;
if (!getCity().equals(ownerDTO.getCity()))
return false;
if (!getTelephone().equals(ownerDTO.getTelephone()))
return false;
return getPets() != null ? getPets().equals(ownerDTO.getPets()) : ownerDTO.getPets() == null;
}
}

View file

@ -85,12 +85,6 @@ public class PetDTO extends NamedDTO {
visit.setPetId(this.getId());
}
@Override
public String toString() {
return "PetDTO{" + "birthDate=" + birthDate + ", type=" + type + ", owner=" + owner + ", visits=" + visits
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
@ -100,15 +94,15 @@ public class PetDTO extends NamedDTO {
if (!super.equals(o))
return false;
PetDTO petDTO = (PetDTO) o;
PetDTO pet = (PetDTO) o;
if (!getBirthDate().equals(petDTO.getBirthDate()))
if (!getBirthDate().equals(pet.getBirthDate()))
return false;
if (!getType().equals(petDTO.getType()))
if (!getType().equals(pet.getType()))
return false;
if (getOwner() != null ? !getOwner().getId().equals(petDTO.getOwner().getId()) : petDTO.getOwner() != null)
if (getOwner() != null ? !getOwner().equals(pet.getOwner()) : pet.getOwner() != null)
return false;
return getVisits() != null ? getVisits().equals(petDTO.getVisits()) : petDTO.getVisits() == null;
return getVisits() != null ? getVisits().equals(pet.getVisits()) : pet.getVisits() == null;
}
}

View file

@ -17,6 +17,7 @@ package org.springframework.samples.petclinic.dto.business;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.samples.petclinic.dto.common.BaseDTO;
import org.springframework.samples.petclinic.model.business.Visit;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDate;
@ -74,14 +75,13 @@ public class VisitDTO extends BaseDTO {
if (!(o instanceof VisitDTO))
return false;
VisitDTO visitDTO = (VisitDTO) o;
VisitDTO visit = (VisitDTO) o;
if (!getDate().equals(visitDTO.getDate()))
if (!getDate().equals(visit.getDate()))
return false;
if (getDescription() != null ? !getDescription().equals(visitDTO.getDescription())
: visitDTO.getDescription() != null)
if (!getDescription().equals(visit.getDescription()))
return false;
return getPetId().equals(visitDTO.getPetId());
return getPetId().equals(visit.getPetId());
}
}

View file

@ -39,9 +39,14 @@ public class BaseDTO implements Serializable {
return this.id == null;
}
@Override
public String toString() {
return "BaseDTO{" + "id=" + id + '}';
}
/*
* @Override public boolean equals(Object o) { if (this == o) return true;
*
* if (!(o instanceof BaseDTO)) return false;
*
* BaseDTO baseDTO = (BaseDTO) o;
*
* return new EqualsBuilder().append(getId(), baseDTO.getId()).isEquals(); }
*/
}

View file

@ -1,5 +1,9 @@
package org.springframework.samples.petclinic.dto.common;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.samples.petclinic.common.CommonError;
import org.springframework.samples.petclinic.common.CommonParameter;
@ -17,6 +21,10 @@ import java.util.UUID;
*
* @author Paul-Emmanuel DOS SANTOS FACAO
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CredentialDTO extends BaseDTO {
@NotNull
@ -40,9 +48,6 @@ public class CredentialDTO extends BaseDTO {
+ CommonParameter.PASSWORD_MIN + " AND " + CommonParameter.PASSWORD_MAX + " !")
private String password;
public CredentialDTO() {
}
public CredentialDTO(UserDTO user) {
this.verified = false;
this.setToken();
@ -52,58 +57,14 @@ public class CredentialDTO extends BaseDTO {
this.password = user.getId().toString();
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public void setDefaultProvider() {
this.provider = CommonParameter.DEFAULT_PROVIDER;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean isVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Date getExpiration() {
return expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setExpiration() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Timestamp(cal.getTime().getTime()));

View file

@ -33,11 +33,6 @@ public class NamedDTO extends BaseDTO {
this.name = name;
}
@Override
public String toString() {
return this.getName();
}
@Override
public boolean equals(Object o) {
if (this == o)
@ -45,9 +40,14 @@ public class NamedDTO extends BaseDTO {
if (!(o instanceof NamedDTO))
return false;
NamedDTO namedDTO = (NamedDTO) o;
NamedDTO that = (NamedDTO) o;
return getName().equals(namedDTO.getName());
return getName().equals(that.getName());
}
@Override
public String toString() {
return this.getName();
}
}

View file

@ -15,6 +15,9 @@
*/
package org.springframework.samples.petclinic.dto.common;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.validation.constraints.NotEmpty;
/**
@ -53,11 +56,11 @@ public class PersonDTO extends BaseDTO {
if (!(o instanceof PersonDTO))
return false;
PersonDTO personDTO = (PersonDTO) o;
PersonDTO person = (PersonDTO) o;
if (!getFirstName().equals(personDTO.getFirstName()))
if (!getFirstName().equals(person.getFirstName()))
return false;
return getLastName().equals(personDTO.getLastName());
return getLastName().equals(person.getLastName());
}
}

View file

@ -1,8 +1,11 @@
package org.springframework.samples.petclinic.dto.common;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.Serializable;
import java.util.Collection;
@ -15,6 +18,7 @@ import java.util.Collection;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class PrivilegeDTO implements Serializable {
private Integer id;
@ -23,4 +27,15 @@ public class PrivilegeDTO implements Serializable {
private Collection<RoleDTO> roles;
/*
* @Override public boolean equals(Object o) { if (this == o) return true;
*
* if (!(o instanceof PrivilegeDTO)) return false;
*
* PrivilegeDTO that = (PrivilegeDTO) o;
*
* return new EqualsBuilder().append(getId(), that.getId()).append(getName(),
* that.getName()) .append(getRoles(), that.getRoles()).isEquals(); }
*/
}

View file

@ -1,8 +1,11 @@
package org.springframework.samples.petclinic.dto.common;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.samples.petclinic.common.CommonParameter;
import javax.validation.constraints.NotEmpty;
@ -19,6 +22,7 @@ import java.util.Collection;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class RoleDTO implements Serializable {
private Integer id;
@ -32,4 +36,16 @@ public class RoleDTO implements Serializable {
private Collection<PrivilegeDTO> privileges;
/*
* @Override public boolean equals(Object o) { if (this == o) return true;
*
* if (!(o instanceof RoleDTO)) return false;
*
* RoleDTO roleDTO = (RoleDTO) o;
*
* return new EqualsBuilder().append(getId(), roleDTO.getId()).append(getName(),
* roleDTO.getName()) .append(getUsers(), roleDTO.getUsers()).append(getPrivileges(),
* roleDTO.getPrivileges()).isEquals(); }
*/
}

View file

@ -2,6 +2,8 @@ package org.springframework.samples.petclinic.dto.common;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.samples.petclinic.common.CommonError;
import org.springframework.samples.petclinic.common.CommonParameter;
import org.springframework.security.core.GrantedAuthority;
@ -154,11 +156,33 @@ public class UserDTO extends PersonDTO implements Serializable, UserDetails {
return getGrantedAuthorities(getPrivileges(this.roles));
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof UserDTO))
return false;
UserDTO userDTO = (UserDTO) o;
return new EqualsBuilder().appendSuper(super.equals(o)).append(isEnabled(), userDTO.isEnabled())
.append(isAccountNonExpired(), userDTO.isAccountNonExpired())
.append(isAccountNonLocked(), userDTO.isAccountNonLocked())
.append(isCredentialsNonExpired(), userDTO.isCredentialsNonExpired())
.append(getEmail(), userDTO.getEmail()).append(getPassword(), userDTO.getPassword())
.append(getMatchingPassword(), userDTO.getMatchingPassword()).append(getRoles(), userDTO.getRoles())
.append(getTelephone(), userDTO.getTelephone()).append(getStreet1(), userDTO.getStreet1())
.append(getStreet2(), userDTO.getStreet2()).append(getStreet3(), userDTO.getStreet3())
.append(getZipCode(), userDTO.getZipCode()).append(getCity(), userDTO.getCity())
.append(getCountry(), userDTO.getCountry()).isEquals();
}
@Override
public String toString() {
return "UserDTO{" + "email='" + email + '\'' + ", password='" + password + '\'' + ", matchingPassword='"
+ matchingPassword + '\'' + ", user enabled=" + enabled + ", account not expired=" + accountNonExpired
+ ", account not locked=" + accountNonLocked + ", credentials not xxpired=" + credentialsNonExpired
+ matchingPassword + '\'' + ", enabled=" + enabled + ", accountNonExpired=" + accountNonExpired
+ ", accountNonLocked=" + accountNonLocked + ", credentialsNonExpired=" + credentialsNonExpired
+ ", roles=" + roles + ", telephone='" + telephone + '\'' + ", street1='" + street1 + '\''
+ ", street2='" + street2 + '\'' + ", street3='" + street3 + '\'' + ", zipCode='" + zipCode + '\''
+ ", city='" + city + '\'' + ", country='" + country + '\'' + '}';

View file

@ -141,7 +141,7 @@ public class Owner extends Person {
@Override
public String toString() {
return new ToStringCreator(this).append(CommonAttribute.ID, this.getId())
return new ToStringCreator(this).append(CommonAttribute.OWNER_ID, this.getId())
.append(CommonAttribute.NEW, this.isNew()).append(CommonAttribute.OWNER_LAST_NAME, this.getLastName())
.append(CommonAttribute.OWNER_FIRST_NAME, this.getFirstName())
.append(CommonAttribute.OWNER_ADDRESS, this.address).append(CommonAttribute.OWNER_CITY, this.city)

View file

@ -1,5 +1,7 @@
package org.springframework.samples.petclinic.model.common;
import lombok.Getter;
import lombok.Setter;
import org.springframework.samples.petclinic.common.CommonError;
import org.springframework.samples.petclinic.common.CommonParameter;
@ -19,6 +21,8 @@ import java.util.UUID;
*/
@Entity(name = "Credential")
@Table(name = "credentials")
@Getter
@Setter
public class Credential extends BaseEntity {
private static final int TOKEN_EXPIRATION = 60 * 24;
@ -50,54 +54,10 @@ public class Credential extends BaseEntity {
@Column(name = "expiration")
private Date expiration;
public Integer getProviderId() {
return providerId;
}
public void setProviderId(Integer providerId) {
this.providerId = providerId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean isVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Date getExpiration() {
return expiration;
}
public void setExpiration(Date expirationDate) {
this.expiration = expirationDate;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setExpiration() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Timestamp(cal.getTime().getTime()));

View file

@ -1,8 +1,6 @@
package org.springframework.samples.petclinic.model.common;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.*;
import org.springframework.samples.petclinic.common.CommonParameter;
import javax.persistence.*;
@ -17,6 +15,7 @@ import java.util.Collection;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Privilege implements Serializable {
@Id
@ -32,4 +31,20 @@ public class Privilege implements Serializable {
@ManyToMany(mappedBy = "privileges", fetch = FetchType.EAGER)
private Collection<Role> roles;
/*
* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o
* instanceof Role)) return false;
*
* Privilege privilege = (Privilege) o;
*
* if (!getId().equals(privilege.getId())) return false; if
* (!getName().equals(privilege.getName())) return false;
*
* return getRoles() != null ? getRoles().equals(privilege.getRoles()) :
* privilege.getRoles() == null; }
*
* @Override public String toString() { return "Privilege{" + "id=" + id + ", name='"
* + name + '\'' + ", roles=" + roles + '}'; }
*/
}

View file

@ -1,8 +1,6 @@
package org.springframework.samples.petclinic.model.common;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.springframework.samples.petclinic.common.CommonParameter;
@ -24,6 +22,7 @@ import java.util.Collection;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Role implements Serializable {
@Id
@ -46,4 +45,17 @@ public class Role implements Serializable {
inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
/*
* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o
* instanceof Role)) return false;
*
* Role role = (Role) o;
*
* if (!getId().equals(role.getId())) return false; if
* (!getName().equals(role.getName())) return false; if (getUsers() == null &&
* role.getUsers() != null) return false; if (getUsers() != null && role.getUsers() ==
* null) return false; return getPrivileges() != null ?
* getPrivileges().equals(role.getPrivileges()) : role.getPrivileges() == null; }
*/
}

View file

@ -2,6 +2,8 @@ package org.springframework.samples.petclinic.model.common;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.samples.petclinic.common.CommonError;
import org.springframework.samples.petclinic.common.CommonParameter;
import org.springframework.security.core.GrantedAuthority;
@ -154,5 +156,32 @@ public class User extends Person implements Serializable, UserDetails {
return getGrantedAuthorities(getPrivileges(this.roles));
}
/*
* @Override public boolean equals(Object o) { if (this == o) return true;
*
* if (!(o instanceof User)) return false;
*
* User user = (User) o;
*
* return new EqualsBuilder().appendSuper(super.equals(o)).append(isEnabled(),
* user.isEnabled()) .append(isAccountNonExpired(), user.isAccountNonExpired())
* .append(isAccountNonLocked(), user.isAccountNonLocked())
* .append(isCredentialsNonExpired(),
* user.isCredentialsNonExpired()).append(getEmail(), user.getEmail())
* .append(getPassword(), user.getPassword()).append(getRoles(), user.getRoles())
* .append(getTelephone(), user.getTelephone()).append(getStreet1(),
* user.getStreet1()) .append(getStreet2(), user.getStreet2()).append(getStreet3(),
* user.getStreet3()) .append(getZipCode(), user.getZipCode()).append(getCity(),
* user.getCity()) .append(getCountry(), user.getCountry()).isEquals(); }
*
* @Override public int hashCode() { return new HashCodeBuilder(17,
* 37).append(getEmail()).append(getPassword()).append(isEnabled())
* .append(isAccountNonExpired()).append(isAccountNonLocked()).append(
* isCredentialsNonExpired())
* .append(getRoles()).append(getTelephone()).append(getStreet1()).append(getStreet2()
* )
* .append(getStreet3()).append(getZipCode()).append(getCity()).append(getCountry()).
* toHashCode(); }
*/
}

View file

@ -0,0 +1,51 @@
package org.springframework.samples.petclinic.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.samples.petclinic.model.common.Privilege;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
/**
* Repository class for <code>Privilege</code> domain objects All method names are
* compliant with Spring Data naming conventions so this interface can easily be extended
* for Spring
*
* @author Paul-Emmanuel DOS SANTOS FACAO
*/
public interface PrivilegeRepository extends Repository<Privilege, Integer> {
/**
* Retrieve a {@link Privilege} from the data store by id.
* @param id the id to search for
* @return the {@link Privilege} if found
*/
@Query("SELECT privilege FROM Privilege privilege join fetch privilege.roles WHERE privilege.id =:id")
@Transactional(readOnly = true)
Privilege findById(@Param("id") Integer id);
/**
* Retrieve a {@link Privilege} from the data store by id.
* @param name the name to search for
* @return the {@link Privilege} if found
*/
@Query("SELECT privilege FROM Privilege privilege left join fetch privilege.roles WHERE privilege.name =:name")
@Transactional(readOnly = true)
Privilege findByName(@Param("name") String name);
/**
* Retrieve all {@link Privilege}s from the data store
* @return a Collection of {@link Privilege}s (or an empty Collection if none
*/
Collection<Privilege> findAll();
/**
* Save a {@link Privilege} to the data store, either inserting or updating it.
* @param privilege the {@link Privilege} to save
* @return the {@link Privilege} saved
*/
Privilege save(Privilege privilege);
}

View file

@ -43,7 +43,15 @@ public interface RoleRepository extends Repository<Role, Integer> {
/**
* Save a {@link Role} to the data store, either inserting or updating it.
* @param role the {@link Role} to save
* @return the {@link Role} saved
*/
Role save(Role role);
/**
* Delete a {@link Role} to the data store.
* @param role the {@link Role} to delete
* @return the {@link Role} deleted
*/
Role delete(Role role);
}

View file

@ -3,12 +3,10 @@ package org.springframework.samples.petclinic.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.samples.petclinic.model.business.Owner;
import org.springframework.samples.petclinic.model.common.User;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
/**
* Repository class for <code>User</code> domain objects All method names are compliant

View file

@ -0,0 +1,95 @@
package org.springframework.samples.petclinic.service.common;
import org.modelmapper.ModelMapper;
import org.springframework.samples.petclinic.dto.common.PrivilegeDTO;
import org.springframework.samples.petclinic.model.common.Privilege;
import org.springframework.samples.petclinic.repository.PrivilegeRepository;
import org.springframework.samples.petclinic.service.business.BaseService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Simple Service between Privilege entity and PrivilegeDTO Data Transfert Object.
*
* @author Paul-Emmanuel DOS SANTOS FACAO
*/
@Service("PrivilegeService")
public class PrivilegeService implements BaseService<Privilege, PrivilegeDTO> {
private final PrivilegeRepository privilegeRepository;
private final ModelMapper modelMapper = new ModelMapper();
public PrivilegeService(PrivilegeRepository privilegeRepository) {
this.privilegeRepository = privilegeRepository;
}
@Override
public Privilege dtoToEntity(PrivilegeDTO dto) {
if (dto != null) {
return modelMapper.map(dto, Privilege.class);
}
return new Privilege();
}
@Override
public PrivilegeDTO entityToDTO(Privilege entity) {
if (entity != null) {
return modelMapper.map(entity, PrivilegeDTO.class);
}
return new PrivilegeDTO();
}
@Override
public List<PrivilegeDTO> entitiesToDTOS(List<Privilege> entities) {
List<PrivilegeDTO> dtos = new ArrayList<>();
entities.forEach(entity -> dtos.add(entityToDTO(entity)));
return dtos;
}
@Override
public List<Privilege> dtosToEntities(List<PrivilegeDTO> dtos) {
List<Privilege> entities = new ArrayList<>();
dtos.forEach(dto -> entities.add(dtoToEntity(dto)));
return entities;
}
@Override
public PrivilegeDTO findById(int id) {
return entityToDTO(privilegeRepository.findById(id));
}
@Override
public List<PrivilegeDTO> findAll() {
Collection<Privilege> privileges = privilegeRepository.findAll();
List<PrivilegeDTO> privilegeDTOS = new ArrayList<>();
privileges.forEach(privilege -> {
privilegeDTOS.add(entityToDTO(privilege));
});
return privilegeDTOS;
}
@Override
public PrivilegeDTO save(PrivilegeDTO dto) {
Privilege privilege = dtoToEntity(dto);
privilege = privilegeRepository.save(privilege);
return entityToDTO(privilege);
}
public PrivilegeDTO findByName(String name) {
return entityToDTO(privilegeRepository.findByName(name));
}
}

View file

@ -12,7 +12,7 @@ import java.util.Collection;
import java.util.List;
/**
* Simple Service between Specialty entity and SpecialtyDTO Data Transfert Object.
* Simple Service between Role entity and RoleDTO Data Transfert Object.
*
* @author Paul-Emmanuel DOS SANTOS FACAO
*/
@ -39,7 +39,9 @@ public class RoleService implements BaseService<Role, RoleDTO> {
@Override
public RoleDTO entityToDTO(Role entity) {
if (entity != null) {
return modelMapper.map(entity, RoleDTO.class);
RoleDTO roleDTO = modelMapper.map(entity, RoleDTO.class);
roleDTO.getUsers().forEach(userDTO -> userDTO.setMatchingPassword(userDTO.getPassword()));
return roleDTO;
}
return new RoleDTO();
@ -63,11 +65,6 @@ public class RoleService implements BaseService<Role, RoleDTO> {
return entities;
}
@Override
public RoleDTO findById(int id) {
return entityToDTO(roleRepository.findById(id));
}
@Override
public List<RoleDTO> findAll() {
Collection<Role> roles = roleRepository.findAll();
@ -80,6 +77,11 @@ public class RoleService implements BaseService<Role, RoleDTO> {
return roleDTOS;
}
@Override
public RoleDTO findById(int id) {
return entityToDTO(roleRepository.findById(id));
}
@Override
public RoleDTO save(RoleDTO dto) {
Role role = dtoToEntity(dto);
@ -88,6 +90,13 @@ public class RoleService implements BaseService<Role, RoleDTO> {
return entityToDTO(role);
}
public RoleDTO delete(RoleDTO dto) {
Role role = dtoToEntity(dto);
role = roleRepository.delete(role);
return entityToDTO(role);
}
public RoleDTO findByName(String name) {
return entityToDTO(roleRepository.findByName(name));
}

View file

@ -38,7 +38,6 @@ public class UserService implements BaseService<User, UserDTO> {
}
User user = modelMapper.map(dto, User.class);
user.setPassword(dto.getPassword());
dto.getRoles().forEach(role -> user.addRole(modelMapper.map(role, Role.class)));
return user;
@ -51,7 +50,6 @@ public class UserService implements BaseService<User, UserDTO> {
}
UserDTO userDto = modelMapper.map(entity, UserDTO.class);
userDto.setPassword(entity.getPassword());
userDto.setMatchingPassword(entity.getPassword());
return userDto;

View file

@ -43,23 +43,9 @@ input:hover,
}
/* add appropriate colors to fb, twitter and google buttons */
.fb {
background-color: #3B5998;
color: white;
}
.twitter {
background-color: #55ACEE;
color: white;
}
.google {
background-color: #dd4b39;
color: white;
}
.github {
background-color: #dd4b39;
.btn-social {
width: 25%;
margin: 10px;
color: white;
}

View file

@ -106,7 +106,7 @@
</div>
</div>
<footer class="navbar" style="position:absolute; bottom:0; width:100%;">
<footer class="navbar" style="position:fixed; bottom:0; width:100%;">
<div id="main-content" class="container">
<div class="row">
<form class="form-inline">
@ -128,7 +128,7 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-noty/2.3.7/packaged/jquery.noty.packaged.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">
<script th:src="@{/js/notification.js}"></script>
<script th:src="@{/resources/js/notification.js}"></script>
<script type="text/javascript">
displayMessage();

View file

@ -17,9 +17,12 @@
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit">Login</button>
<a href="/register" class="btn btn-default" ><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
<span>Register</span></a>
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-log-in" aria-hidden="true"> Login</span>
</button>
<a href="/register" class="btn btn-default" >
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> Register</span>
</a>
</div>
</div>
@ -28,13 +31,13 @@
<h2 style="text-align:center">Login with Social Media</h2>
<div class="col-md-12 " th:each="url : ${urls}" style="text-align:center">
<a th:if="${url.key == 'Google'}" th:href="${url.value}" class="btn btn-bloc" style="background-color: #dd4b39;color: white">
<a th:if="${url.key == 'Google'}" th:href="${url.value}" class="btn btn-bloc btn-social btn-lg" style="background-color: #dd4b39">
<i class="fa fa-google fa-fw"></i> Login with Google
</a>
<a th:if="${url.key == 'GitHub'}" th:href="${url.value}" class="btn btn-bloc" style="background-color: white;color: black">
<a th:if="${url.key == 'GitHub'}" th:href="${url.value}" class="btn btn-bloc btn-social btn-lg" style="background-color: black">
<i class="fa fa-github fa-fw"></i> Login with Github
</a>
<a th:if="${url.key == 'Facebook'}" th:href="${url.value}" class="btn btn-bloc" style="background-color: #3B5998;color: white">
<a th:if="${url.key == 'Facebook'}" th:href="${url.value}" class="btn btn-bloc btn-social btn-lg" style="background-color: #3B5998">
<i class="fa fa-facebook fa-fw"></i> Login with Facebook
</a>

View file

@ -32,6 +32,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
@ -65,9 +66,20 @@ import org.springframework.test.web.servlet.MockMvc;
includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE))
@RunWith(SpringRunner.class)
@ExtendWith(MockitoExtension.class)
@AutoConfigureTestDatabase
class PetControllerTest {
private static final int TEST_OWNER_ID = 1;
private static final int OWNER_ID = 15;
private static final String OWNER_FIRST_NAME = "Joe";
private static final String OWNER_LAST_NAME = "BLOGGS";
private static final String OWNER_ADDRESS = "123 Caramel Street";
private static final String OWNER_CITY = "London";
private static final String OWNER_PHONE = "6085551023";
private static final int TEST_PET_ID = 1;
@ -91,13 +103,21 @@ class PetControllerTest {
@BeforeEach
void beforeEach() {
PetTypeDTO cat = new PetTypeDTO();
cat.setId(3);
cat.setName("hamster");
PetTypeDTO petTypeDTO = new PetTypeDTO();
petTypeDTO.setId(3);
petTypeDTO.setName("hamster");
OwnerDTO ownerDTO = new OwnerDTO();
ownerDTO = new OwnerDTO();
ownerDTO.setId(OWNER_ID);
ownerDTO.setFirstName(OWNER_FIRST_NAME);
ownerDTO.setLastName(OWNER_LAST_NAME);
ownerDTO.setAddress(OWNER_ADDRESS);
ownerDTO.setCity(OWNER_CITY);
ownerDTO.setTelephone(OWNER_PHONE);
given(this.ownerService.findById(TEST_OWNER_ID)).willReturn(new OwnerDTO());
given(this.ownerService.findById(OWNER_ID)).willReturn(ownerDTO);
given(this.petService.findById(TEST_PET_ID)).willReturn(new PetDTO());
given(this.petService.findPetTypes()).willReturn(Lists.newArrayList(cat));
given(this.petService.findPetTypes()).willReturn(Lists.newArrayList(petTypeDTO));
}
@Test
@ -105,7 +125,7 @@ class PetControllerTest {
@Tag("initCreationForm")
@DisplayName("Verify that Pet creation form is initialized")
void givenOwnerId_whenAskToCreatePet_thenDisplayCreationViewWithRightPet() throws Exception {
mockMvc.perform(get(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, TEST_OWNER_ID))
mockMvc.perform(get(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, OWNER_ID))
.andExpect(status().is2xxSuccessful()).andExpect(view().name(CommonView.PET_CREATE_OR_UPDATE))
.andExpect(model().attributeExists(CommonAttribute.PET));
}
@ -115,7 +135,7 @@ class PetControllerTest {
@Tag("processCreationForm")
@DisplayName("Verify that call the right view with parameters when attempt to create Pet")
void givenNewPet_whenPostNewPet_thenSavePetAndRedirectToOwnerView() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, TEST_OWNER_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, OWNER_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_TYPE, "hamster")
.param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12")).andExpect(status().is3xxRedirection())
.andExpect(view().name(CommonView.OWNER_OWNERS_ID_R));
@ -126,7 +146,7 @@ class PetControllerTest {
@Tag("processCreationForm")
@DisplayName("Verify that return to Pet creation form when pet has no name")
void givenNewPetWithoutName_whenPostNewPet_thenRedirectToPetUpdate() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, TEST_OWNER_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, OWNER_ID)
.param(CommonAttribute.PET_TYPE, "hamster").param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12"))
.andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER))
.andExpect(model().attributeHasErrors(CommonAttribute.PET))
@ -142,7 +162,7 @@ class PetControllerTest {
@DisplayName("Verify that return to Pet creation form when pet has no type")
void givenNewPetWithoutType_whenPostNewPet_thenRedirectToPetUpdate() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, TEST_OWNER_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, OWNER_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12"))
.andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER))
.andExpect(model().attributeHasErrors(CommonAttribute.PET))
@ -172,7 +192,7 @@ class PetControllerTest {
@DisplayName("Verify that return to Pet creation form when pet has no birth date")
void givenNewPetWithoutBirthDate_whenPostNewPet_thenRedirectToPetUpdate() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, TEST_OWNER_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_NEW, OWNER_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_TYPE, "hamster"))
.andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER))
.andExpect(model().attributeHasErrors(CommonAttribute.PET))
@ -187,7 +207,7 @@ class PetControllerTest {
@Tag("initUpdateForm")
@DisplayName("Verify that Pet update form is initialized with the right Pet")
void givenPetId_whenGetUpdatePet_thenReturnUpdateViewWithPet() throws Exception {
mockMvc.perform(get(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, TEST_OWNER_ID, TEST_PET_ID))
mockMvc.perform(get(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, OWNER_ID, TEST_PET_ID))
.andExpect(status().isOk()).andExpect(model().attributeExists(CommonAttribute.PET))
.andExpect(view().name(CommonView.PET_CREATE_OR_UPDATE));
}
@ -196,7 +216,7 @@ class PetControllerTest {
@WithMockUser(value = WebSecurityConfig.TEST_USER)
@Tag("processUpdateForm")
void givenOwnerAndModifiedPet_whenAskToUpdatePet_thenUpdatePetAndDisplayOwnerView() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, TEST_OWNER_ID, TEST_PET_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, OWNER_ID, TEST_PET_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_TYPE, "hamster")
.param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12")).andExpect(status().is3xxRedirection())
.andExpect(view().name(CommonView.OWNER_OWNERS_ID_R));
@ -206,7 +226,7 @@ class PetControllerTest {
@WithMockUser(value = WebSecurityConfig.TEST_USER)
@Tag("processUpdateForm")
void testProcessUpdateFormHasErrors() throws Exception {
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, TEST_OWNER_ID, TEST_PET_ID)
mockMvc.perform(post(CommonEndPoint.OWNERS_ID + CommonEndPoint.PETS_ID_EDIT, OWNER_ID, TEST_PET_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12"))
.andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER))
.andExpect(model().attributeHasErrors(CommonAttribute.PET)).andExpect(status().isOk())

View file

@ -92,7 +92,7 @@ class VisitControllerIntegrationTest {
expected.setDate(LocalDate.now());
expected.setPetId(PET_ID);
assertThat(found.getVisits()).contains(expected);
assertThat(found.getVisits()).usingElementComparatorOnFields("petId", "date").contains(expected);
}
@Test

View file

@ -136,7 +136,7 @@ class VisitControllerTest {
expected.setDate(LocalDate.now());
expected.setPetId(PET_ID);
assertThat(found.getVisits()).contains(expected);
assertThat(found.getVisits()).usingElementComparatorOnFields("petId", "date").contains(expected);
}
@Test

View file

@ -23,7 +23,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.samples.petclinic.controller.WebSecurityConfig;
import org.springframework.samples.petclinic.controller.common.CrashController;
import org.springframework.samples.petclinic.service.common.UserDetailsServiceImpl;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

View file

@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.samples.petclinic.service;
package org.springframework.samples.petclinic.service.business;
import static org.assertj.core.api.Assertions.assertThat;
@ -25,7 +25,6 @@ import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.samples.petclinic.model.business.Owner;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.model.business.Pet;
@ -35,7 +34,7 @@ import org.springframework.samples.petclinic.model.business.Vet;
import org.springframework.samples.petclinic.repository.VetRepository;
import org.springframework.samples.petclinic.model.business.Visit;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.stereotype.Service;
import org.springframework.samples.petclinic.service.EntityUtils;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

View file

@ -1,4 +1,4 @@
package org.springframework.samples.petclinic.service;
package org.springframework.samples.petclinic.service.business;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
@ -19,9 +19,6 @@ import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.samples.petclinic.repository.PetTypeRepository;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.samples.petclinic.service.business.OwnerService;
import org.springframework.samples.petclinic.service.business.PetService;
import org.springframework.samples.petclinic.service.business.PetTypeService;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDate;
@ -134,7 +131,6 @@ class OwnerServiceTest {
for (Pet pet : found.getPets()) {
assertThat(owner.getPets()).extracting("id").contains(pet.getId());
}
}
@Test

View file

@ -1,4 +1,4 @@
package org.springframework.samples.petclinic.service;
package org.springframework.samples.petclinic.service.business;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;

View file

@ -1,4 +1,4 @@
package org.springframework.samples.petclinic.service;
package org.springframework.samples.petclinic.service.business;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;

View file

@ -0,0 +1,221 @@
package org.springframework.samples.petclinic.service.common;
import org.junit.jupiter.api.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.samples.petclinic.dto.common.PrivilegeDTO;
import org.springframework.samples.petclinic.dto.common.RoleDTO;
import org.springframework.samples.petclinic.dto.common.UserDTO;
import org.springframework.samples.petclinic.model.common.Privilege;
import org.springframework.samples.petclinic.model.common.Role;
import org.springframework.samples.petclinic.model.common.User;
import org.springframework.samples.petclinic.repository.RoleRepository;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@AutoConfigureTestDatabase
@SpringBootTest
@RunWith(SpringRunner.class)
class RoleServiceTest {
private final static Integer USER_ID = 2;
private final static Integer ROLE_ID = 4;
private final static Integer PRIVILEGE_ID = 3;
private final static String ROLE_NAME = "ROLE_TEST";
@Autowired
private RoleRepository roleRepository;
@Autowired
private UserService userService;
@Autowired
private PrivilegeService privilegeService;
private RoleService roleService;
private User user;
private UserDTO userDTO;
private Role role;
private RoleDTO roleDTO;
private Privilege privilege;
private PrivilegeDTO privilegeDTO;
@BeforeEach
void beforeEach() {
userDTO = userService.findById(USER_ID);
user = userService.dtoToEntity(userDTO);
privilegeDTO = privilegeService.findById(PRIVILEGE_ID);
privilege = privilegeService.dtoToEntity(privilegeDTO);
roleService = new RoleService(roleRepository);
role = new Role();
role.setId(ROLE_ID);
role.setName(ROLE_NAME);
role.setUsers(Collections.singleton(user));
role.setPrivileges(Collections.singleton(privilege));
user.setRoles(Collections.singleton(role));
roleDTO = new RoleDTO();
roleDTO.setId(ROLE_ID);
roleDTO.setName(ROLE_NAME);
roleDTO.setUsers(Collections.singleton(userDTO));
roleDTO.setPrivileges(Collections.singleton(privilegeDTO));
userDTO.setRoles(Collections.singleton(roleDTO));
}
@Test
@Tag("dtoToEntity")
@DisplayName("Verify the convertion from DTO to Entity")
void dtoToEntity() {
Role found = roleService.dtoToEntity(roleDTO);
assertThat(found.getId()).isEqualTo(role.getId());
assertThat(found.getName()).isEqualTo(role.getName());
assertThat(found.getUsers()).usingElementComparatorIgnoringFields("roles").contains(user);
assertThat(found.getPrivileges()).usingElementComparatorIgnoringFields("roles").contains(privilege);
}
@Test
@Tag("entityToDTO")
@DisplayName("Verify the convertion from Entity to DTO")
void entityToDTO() {
RoleDTO found = roleService.entityToDTO(role);
assertThat(found.getId()).isEqualTo(roleDTO.getId());
assertThat(found.getName()).isEqualTo(roleDTO.getName());
assertThat(found.getUsers()).usingElementComparatorIgnoringFields("roles").contains(userDTO);
assertThat(found.getPrivileges()).usingElementComparatorIgnoringFields("roles").contains(privilegeDTO);
}
@Test
@Tag("dtosToEntities")
@DisplayName("Verify the convertion from DTOs list to Entities list")
void dtosToEntities() {
List<RoleDTO> roleDTOS = roleService.findAll();
List<Role> expected = new ArrayList<>();
roleDTOS.forEach(dto -> expected.add(roleService.dtoToEntity(dto)));
List<Role> found = roleService.dtosToEntities(roleDTOS);
assertThat(found).hasSameSizeAs(expected);
for (int i = 0; i < found.size(); i++) {
assertThat(found.get(i).getId()).isEqualTo(expected.get(i).getId());
assertThat(found.get(i).getName()).isEqualTo(expected.get(i).getName());
assertThat(found.get(i).getUsers()).usingElementComparatorIgnoringFields("roles")
.contains(expected.get(i).getUsers().toArray(new User[0]));
assertThat(found.get(i).getPrivileges()).usingElementComparatorIgnoringFields("roles")
.contains(expected.get(i).getPrivileges().toArray(new Privilege[0]));
}
}
@Test
@Tag("entitiesToDTOS")
@DisplayName("Verify the convertion from Entities list to DTOs list")
void entitiesToDTOS() {
List<RoleDTO> expected = roleService.findAll();
List<Role> roles = new ArrayList<>();
expected.forEach(dto -> roles.add(roleService.dtoToEntity(dto)));
List<RoleDTO> found = roleService.entitiesToDTOS(roles);
assertThat(found).hasSameSizeAs(expected);
for (int i = 0; i < found.size(); i++) {
assertThat(found.get(i).getId()).isEqualTo(expected.get(i).getId());
assertThat(found.get(i).getName()).isEqualTo(expected.get(i).getName());
assertThat(found.get(i).getUsers()).usingElementComparatorIgnoringFields("roles")
.contains(expected.get(i).getUsers().toArray(new UserDTO[0]));
assertThat(found.get(i).getPrivileges()).usingElementComparatorIgnoringFields("roles")
.contains(expected.get(i).getPrivileges().toArray(new PrivilegeDTO[0]));
}
}
@Test
@Tag("findById")
@DisplayName("Verify that we get RoleDTO by his ID")
void findById() {
List<RoleDTO> allDTO = roleService.findAll();
RoleDTO expected = allDTO.get(2);
RoleDTO found = roleService.findById(expected.getId());
assertThat(found.getId()).isEqualTo(expected.getId());
assertThat(found.getName()).isEqualTo(expected.getName());
assertThat(found.getUsers()).usingElementComparatorIgnoringFields("roles")
.contains(expected.getUsers().toArray(new UserDTO[0]));
assertThat(found.getPrivileges()).usingElementComparatorIgnoringFields("roles")
.contains(expected.getPrivileges().toArray(new PrivilegeDTO[0]));
}
@Test
@Tag("findAll")
@DisplayName("Verify that the RoleDTO list contain all previous elements and the new saved one")
void findAll() {
List<RoleDTO> expected = roleService.findAll();
roleDTO.setUsers(new HashSet<>());
assertThat(expected).doesNotContain(roleDTO);
RoleDTO saved = roleService.save(roleDTO);
List<RoleDTO> found = roleService.findAll();
assertThat(found).hasSize(expected.size() + 1).usingElementComparatorOnFields("id", "name")
.containsOnlyOnceElementsOf(expected).contains(roleDTO);
roleService.delete(saved);
}
@Test
@Tag("findByName")
@DisplayName("Verify that we get RoleDTO by his Name")
void findByName() {
RoleDTO expected = roleService.findById(1);
RoleDTO found = roleService.findByName(expected.getName());
assertThat(found.getId()).isEqualTo(expected.getId());
assertThat(found.getName()).isEqualTo(expected.getName());
assertThat(found.getUsers()).usingElementComparatorIgnoringFields("roles")
.contains(expected.getUsers().toArray(new UserDTO[0]));
assertThat(found.getPrivileges()).usingElementComparatorIgnoringFields("roles")
.contains(expected.getPrivileges().toArray(new PrivilegeDTO[0]));
}
@Test
@Tag("save")
@DisplayName("Verify that all RoleDTO list contain the new saved one")
void save() {
assertThat(roleService.findAll()).doesNotContain(roleDTO);
roleDTO.setUsers(new HashSet<>());
RoleDTO saved = roleService.save(roleDTO);
RoleDTO found = roleService.findById(saved.getId());
assertThat(found.getId()).isEqualTo(saved.getId());
assertThat(found.getName()).isEqualTo(saved.getName());
assertThat(found.getUsers()).usingElementComparatorIgnoringFields("roles")
.contains(saved.getUsers().toArray(new UserDTO[0]));
assertThat(found.getPrivileges()).usingElementComparatorIgnoringFields("roles")
.contains(saved.getPrivileges().toArray(new PrivilegeDTO[0]));
RoleDTO deleted = roleService.delete(saved);
}
}