solve bug of fechType

This commit is contained in:
PEDSF 2020-11-30 19:39:39 +01:00
parent bf2d2a7773
commit 834dd29bc7
19 changed files with 43 additions and 62 deletions

View file

@ -1,7 +1,6 @@
package org.springframework.samples.petclinic.configuration; package org.springframework.samples.petclinic.configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry; import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer; import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;
@ -28,4 +27,5 @@ public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBroker
protected boolean sameOriginDisabled() { protected boolean sameOriginDisabled() {
return true; return true;
} }
} }

View file

@ -20,6 +20,8 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; 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 javax.annotation.Resource;
import java.util.Arrays; import java.util.Arrays;
@ -125,10 +127,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
return CommonOAuth2Provider.GITHUB.getBuilder(client).clientId(clientId).clientSecret(clientSecret).build(); return CommonOAuth2Provider.GITHUB.getBuilder(client).clientId(clientId).clientSecret(clientSecret).build();
} }
if (client.equals("twitter")) {
return ClientRegistration.withRegistrationId("twitter").clientId(clientId).clientSecret(clientSecret).build();
}
return null; return null;
} }

View file

@ -30,7 +30,7 @@ public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfi
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry config) { public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/public"); config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app"); config.setApplicationDestinationPrefixes("/app");
} }
@ -39,8 +39,6 @@ public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfi
registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS(); registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
} }
@Override @Override
protected boolean sameOriginDisabled() { protected boolean sameOriginDisabled() {
return true; return true;

View file

@ -16,7 +16,6 @@
package org.springframework.samples.petclinic.controller; package org.springframework.samples.petclinic.controller;
import org.springframework.samples.petclinic.common.*; import org.springframework.samples.petclinic.common.*;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.business.OwnerDTO; import org.springframework.samples.petclinic.dto.business.OwnerDTO;
import org.springframework.samples.petclinic.dto.business.PetDTO; import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.service.business.OwnerService; import org.springframework.samples.petclinic.service.business.OwnerService;

View file

@ -17,7 +17,6 @@ package org.springframework.samples.petclinic.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.common.*; import org.springframework.samples.petclinic.common.*;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.business.OwnerDTO; import org.springframework.samples.petclinic.dto.business.OwnerDTO;
import org.springframework.samples.petclinic.dto.business.PetDTO; import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.dto.business.PetTypeDTO; import org.springframework.samples.petclinic.dto.business.PetTypeDTO;
@ -84,8 +83,8 @@ class PetController extends WebSocketSender {
} }
@PostMapping(CommonEndPoint.PETS_NEW) @PostMapping(CommonEndPoint.PETS_NEW)
public String processCreationForm(@ModelAttribute("owner") OwnerDTO owner, @Valid PetDTO pet, BindingResult result, public String processCreationForm(@ModelAttribute("owner") OwnerDTO owner, @ModelAttribute("pet") @Valid PetDTO pet,
ModelMap model) { BindingResult result, ModelMap model) {
if (owner == null) { if (owner == null) {
sendErrorMessage(CommonWebSocket.PET_CREATION_ERROR); sendErrorMessage(CommonWebSocket.PET_CREATION_ERROR);
result.rejectValue(CommonAttribute.OWNER, CommonError.NOT_FOUND_ARGS, CommonError.NOT_FOUND_MESSAGE); result.rejectValue(CommonAttribute.OWNER, CommonError.NOT_FOUND_ARGS, CommonError.NOT_FOUND_MESSAGE);
@ -118,8 +117,8 @@ class PetController extends WebSocketSender {
} }
@PostMapping("/pets/{petId}/edit") @PostMapping("/pets/{petId}/edit")
public String processUpdateForm(@Valid PetDTO pet, BindingResult result, @ModelAttribute("owner") OwnerDTO owner, public String processUpdateForm(@ModelAttribute("pet") @Valid PetDTO pet, BindingResult result,
ModelMap model) { @ModelAttribute("owner") OwnerDTO owner, ModelMap model) {
if (result.hasErrors()) { if (result.hasErrors()) {
pet.setOwner(owner); pet.setOwner(owner);
model.put(CommonAttribute.PET, pet); model.put(CommonAttribute.PET, pet);

View file

@ -5,7 +5,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType; import org.springframework.core.ResolvableType;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.samples.petclinic.common.*; import org.springframework.samples.petclinic.common.*;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.common.CredentialDTO; import org.springframework.samples.petclinic.dto.common.CredentialDTO;
import org.springframework.samples.petclinic.dto.common.MessageDTO; import org.springframework.samples.petclinic.dto.common.MessageDTO;
import org.springframework.samples.petclinic.dto.common.UserDTO; import org.springframework.samples.petclinic.dto.common.UserDTO;

View file

@ -19,7 +19,6 @@ import org.springframework.samples.petclinic.common.CommonAttribute;
import org.springframework.samples.petclinic.common.CommonEndPoint; import org.springframework.samples.petclinic.common.CommonEndPoint;
import org.springframework.samples.petclinic.common.CommonView; import org.springframework.samples.petclinic.common.CommonView;
import org.springframework.samples.petclinic.common.CommonWebSocket; import org.springframework.samples.petclinic.common.CommonWebSocket;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.business.VetsDTO; import org.springframework.samples.petclinic.dto.business.VetsDTO;
import org.springframework.samples.petclinic.service.business.VetService; import org.springframework.samples.petclinic.service.business.VetService;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;

View file

@ -23,7 +23,6 @@ import org.springframework.samples.petclinic.common.CommonAttribute;
import org.springframework.samples.petclinic.common.CommonEndPoint; import org.springframework.samples.petclinic.common.CommonEndPoint;
import org.springframework.samples.petclinic.common.CommonView; import org.springframework.samples.petclinic.common.CommonView;
import org.springframework.samples.petclinic.common.CommonWebSocket; import org.springframework.samples.petclinic.common.CommonWebSocket;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.business.PetDTO; import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.dto.business.VisitDTO; import org.springframework.samples.petclinic.dto.business.VisitDTO;
import org.springframework.samples.petclinic.service.business.PetService; import org.springframework.samples.petclinic.service.business.PetService;

View file

@ -1,4 +1,4 @@
package org.springframework.samples.petclinic.controller.common; package org.springframework.samples.petclinic.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.SimpMessagingTemplate;
@ -16,7 +16,6 @@ public class WebSocketSender {
@Autowired @Autowired
SimpMessagingTemplate simpMessagingTemplate; SimpMessagingTemplate simpMessagingTemplate;
public void sendMessage(String message, String type) { public void sendMessage(String message, String type) {
// Send message asynchronously // Send message asynchronously
new Thread(new Runnable() { new Thread(new Runnable() {

View file

@ -85,6 +85,12 @@ public class PetDTO extends NamedDTO {
visit.setPetId(this.getId()); visit.setPetId(this.getId());
} }
@Override
public String toString() {
return "PetDTO{" + "birthDate=" + birthDate + ", type=" + type + ", owner=" + owner + ", visits=" + visits
+ '}';
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o)

View file

@ -105,22 +105,20 @@ public class Owner extends Person {
} }
public void addPet(Pet pet) { public void addPet(Pet pet) {
if (pet.isNew()) {
if (this.pets == null) { getPetsInternal().add(pet);
this.pets = new HashSet<>();
} }
try {
if (!this.getPets().contains(pet)) {
getPetsInternal().add(pet);
}
}
catch (Exception exception) {
this.pets = new HashSet<>();
this.pets.add(pet);
}
pet.setOwner(this); pet.setOwner(this);
} }
/*
* public void addPet(Pet pet) {
*
* if (this.pets == null) { this.pets = new HashSet<>(); } try { if
* (!this.getPets().contains(pet)) { getPetsInternal().add(pet); } } catch (Exception
* exception) { this.pets = new HashSet<>(); this.pets.add(pet); }
*
* pet.setOwner(this); }
*/
/** /**
* Return the Pet with the given name, or null if none found for this Owner. * Return the Pet with the given name, or null if none found for this Owner.

View file

@ -54,14 +54,6 @@ public class User extends Person implements Serializable, UserDetails {
@Column(name = "credential_unexpired") @Column(name = "credential_unexpired")
private boolean credentialsNonExpired; private boolean credentialsNonExpired;
/*
* @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
*
* @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id",
* referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id",
* referencedColumnName = "id")) private Set<Role> roles;
*/
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))

View file

@ -54,7 +54,7 @@ public interface OwnerRepository extends Repository<Owner, Integer> {
* @param id the id to search for * @param id the id to search for
* @return the {@link Owner} if found * @return the {@link Owner} if found
*/ */
@Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id") @Query("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id")
@Transactional(readOnly = true) @Transactional(readOnly = true)
Owner findById(@Param("id") Integer id); Owner findById(@Param("id") Integer id);
@ -62,6 +62,8 @@ public interface OwnerRepository extends Repository<Owner, Integer> {
* Retrieve all {@link Owner}s from the data store * Retrieve all {@link Owner}s from the data store
* @return a Collection of {@link Owner}s (or an empty Collection if none * @return a Collection of {@link Owner}s (or an empty Collection if none
*/ */
@Query("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets")
@Transactional(readOnly = true)
List<Owner> findAll(); List<Owner> findAll();
/** /**

View file

@ -100,20 +100,6 @@ public class OwnerService implements BaseService<Owner, OwnerDTO> {
public List<OwnerDTO> findAll() { public List<OwnerDTO> findAll() {
List<Owner> owners = ownerRepository.findAll(); List<Owner> owners = ownerRepository.findAll();
// Add pets for each owners
owners.forEach(owner -> {
// Find owner pets
List<Pet> pets = petRepository.findByOwnerId(owner.getId());
pets.forEach(pet -> {
// Add pet to the owner
owner.addPet(pet);
// Add owner to the pet
pet.setOwner(owner);
});
});
return entitiesToDTOS(owners); return entitiesToDTOS(owners);
} }

View file

@ -26,11 +26,10 @@ spring.resources.cache.cachecontrol.max-age=12h
########################################################################## DEBUG ########################################################################## DEBUG
#logging.level.root=DEBUG #logging.level.root=DEBUG
#logging.level.org.springframework.web: DEBUG
#logging.level.org.hibernate: DEBUG #logging.level.org.hibernate: DEBUG
#logging.level.org.springframework.context.annotation=TRACE #logging.level.org.springframework.context.annotation=TRACE
logging.level.org.springframework.security=TRACE #logging.level.org.springframework.security=TRACE
logging.level.org.springframework.web=TRACE #logging.level.org.springframework.web=TRACE
spring.datasource.hikari.connectionTimeout=20000 spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5 spring.datasource.hikari.maximumPoolSize=5

View file

@ -1,8 +1,7 @@
var stompClient = null;
function displayMessage() { function displayMessage() {
var socket = new SockJS('/websocket'); var socket = new SockJS('/websocket');
stompClient = Stomp.over(socket); var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) { stompClient.connect({}, function (frame) {
stompClient.subscribe('/topic/public', function (socketMessage) { stompClient.subscribe('/topic/public', function (socketMessage) {

View file

@ -36,7 +36,6 @@ import org.springframework.samples.petclinic.common.CommonAttribute;
import org.springframework.samples.petclinic.common.CommonEndPoint; import org.springframework.samples.petclinic.common.CommonEndPoint;
import org.springframework.samples.petclinic.common.CommonError; import org.springframework.samples.petclinic.common.CommonError;
import org.springframework.samples.petclinic.common.CommonView; import org.springframework.samples.petclinic.common.CommonView;
import org.springframework.samples.petclinic.controller.common.WebSocketSender;
import org.springframework.samples.petclinic.dto.business.OwnerDTO; import org.springframework.samples.petclinic.dto.business.OwnerDTO;
import org.springframework.samples.petclinic.dto.business.PetDTO; import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.dto.business.PetTypeDTO; import org.springframework.samples.petclinic.dto.business.PetTypeDTO;

View file

@ -28,7 +28,9 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
@ -47,9 +49,12 @@ import org.springframework.samples.petclinic.service.business.OwnerService;
import org.springframework.samples.petclinic.service.business.PetService; import org.springframework.samples.petclinic.service.business.PetService;
import org.springframework.samples.petclinic.service.business.PetTypeService; import org.springframework.samples.petclinic.service.business.PetTypeService;
import org.springframework.samples.petclinic.service.common.UserDetailsServiceImpl; import org.springframework.samples.petclinic.service.common.UserDetailsServiceImpl;
import org.springframework.samples.petclinic.validator.PetDTOValidator;
import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
/** /**
* Test class for the {@link PetController} * Test class for the {@link PetController}
@ -60,6 +65,7 @@ import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(value = PetController.class, @WebMvcTest(value = PetController.class,
includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE))
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@ExtendWith(MockitoExtension.class)
class PetControllerTest { class PetControllerTest {
private static final int TEST_OWNER_ID = 1; private static final int TEST_OWNER_ID = 1;
@ -136,6 +142,7 @@ class PetControllerTest {
@Tag("processCreationForm") @Tag("processCreationForm")
@DisplayName("Verify that return to Pet creation form when pet has no type") @DisplayName("Verify that return to Pet creation form when pet has no type")
void givenNewPetWithoutType_whenPostNewPet_thenRedirectToPetUpdate() throws Exception { 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, TEST_OWNER_ID)
.param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12")) .param(CommonAttribute.PET_NAME, "Betty").param(CommonAttribute.PET_BIRTH_DATE, "2015-02-12"))
.andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER)) .andExpect(model().attributeHasNoErrors(CommonAttribute.OWNER))

View file

@ -16,6 +16,7 @@
package org.springframework.samples.petclinic.validator; package org.springframework.samples.petclinic.validator;
import java.util.Arrays;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
@ -55,7 +56,9 @@ class ValidatorTest {
assertThat(constraintViolations).hasSize(2); assertThat(constraintViolations).hasSize(2);
ConstraintViolation<Person> violation = constraintViolations.iterator().next(); ConstraintViolation<Person> violation = constraintViolations.iterator().next();
assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
assertThat(violation.getMessage()).isEqualTo("must not be empty");
assertThat(Arrays.asList("Length should be between : 2 AND 50 !", "must not be empty"))
.contains(violation.getMessage());
} }
} }