From a97d0fb7d5dc03ebbe874bfbb037e81e8dec9672 Mon Sep 17 00:00:00 2001 From: xabier_aldama Date: Fri, 8 Oct 2021 09:27:39 +0200 Subject: [PATCH 1/4] Updated to springboot 2.4.11 --- pom.xml | 2 +- spring-petclinic-server/pom.xml | 5 + .../petclinic/model/ValidatorTests.java | 39 ++- .../service/AbstractClinicServiceTests.java | 245 +++++++++--------- .../petclinic/web/PetResourceTests.java | 76 +++--- .../petclinic/web/VetResourceTests.java | 49 ++-- 6 files changed, 213 insertions(+), 203 deletions(-) diff --git a/pom.xml b/pom.xml index ed6866ff..3b92e4ec 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.RELEASE + 2.4.11 org.springframework.samples diff --git a/spring-petclinic-server/pom.xml b/spring-petclinic-server/pom.xml index 2c41de44..4866fed8 100644 --- a/spring-petclinic-server/pom.xml +++ b/spring-petclinic-server/pom.xml @@ -52,6 +52,11 @@ spring-boot-configuration-processor true + + + org.springframework.boot + spring-boot-starter-validation + org.springframework.samples diff --git a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java index e9760f12..f6a5e171 100644 --- a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java +++ b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java @@ -8,40 +8,39 @@ import javax.validation.ConstraintViolation; import javax.validation.Validator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; /** * - * @author Michael Isvy - * Simple test to make sure that Bean Validation is working - * (useful when upgrading to a new version of Hibernate Validator/ Bean Validation) + * @author Michael Isvy Simple test to make sure that Bean Validation is working (useful when upgrading to a new version of Hibernate + * Validator/ Bean Validation) * */ public class ValidatorTests { private Validator createValidator() { - LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); - localValidatorFactoryBean.afterPropertiesSet(); - return localValidatorFactoryBean; - } + LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); + localValidatorFactoryBean.afterPropertiesSet(); + return localValidatorFactoryBean; + } @Test - public void shouldNotValidateWhenFirstNameEmpty() { + public void shouldNotValidateWhenFirstNameEmpty() { - LocaleContextHolder.setLocale(Locale.ENGLISH); - Person person = new Person(); - person.setFirstName(""); - person.setLastName("smith"); + LocaleContextHolder.setLocale(Locale.ENGLISH); + Person person = new Person(); + person.setFirstName(""); + person.setLastName("smith"); - Validator validator = createValidator(); - Set> constraintViolations = validator.validate(person); + Validator validator = createValidator(); + Set> constraintViolations = validator.validate(person); - assertThat(constraintViolations.size()).isEqualTo(1); - ConstraintViolation violation = constraintViolations.iterator().next(); - assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); - assertThat(violation.getMessage()).isEqualTo("must not be empty"); - } + assertThat(constraintViolations.size()).isEqualTo(1); + ConstraintViolation violation = constraintViolations.iterator().next(); + assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); + assertThat(violation.getMessage()).isEqualTo("must not be empty"); + } } diff --git a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/service/AbstractClinicServiceTests.java b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/service/AbstractClinicServiceTests.java index 50758829..1e47a7ef 100644 --- a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/service/AbstractClinicServiceTests.java +++ b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/service/AbstractClinicServiceTests.java @@ -15,7 +15,12 @@ */ package org.springframework.samples.petclinic.service; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.Date; + +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Owner; import org.springframework.samples.petclinic.model.Pet; @@ -25,22 +30,25 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; -import java.util.Collection; -import java.util.Date; - -import static org.assertj.core.api.Assertions.assertThat; - /** - *

Base class for {@link ClinicService} integration tests.

Subclasses should specify Spring context - * configuration using {@link ContextConfiguration @ContextConfiguration} annotation

- * AbstractclinicServiceTests and its subclasses benefit from the following services provided by the Spring - * TestContext Framework:

  • Spring IoC container caching which spares us unnecessary set up - * time between test execution.
  • Dependency Injection of test fixture instances, meaning that - * we don't need to perform application context lookups. See the use of {@link Autowired @Autowired} on the instance variable, which uses autowiring by - * type.
  • Transaction management, meaning each test method is executed in its own transaction, - * which is automatically rolled back by default. Thus, even if tests insert or otherwise change database state, there - * is no need for a teardown or cleanup script.
  • An {@link org.springframework.context.ApplicationContext - * ApplicationContext} is also inherited and can be used for explicit bean lookup if necessary.
+ *

+ * Base class for {@link ClinicService} integration tests. + *

+ *

+ * Subclasses should specify Spring context configuration using {@link ContextConfiguration @ContextConfiguration} annotation + *

+ *

+ * AbstractclinicServiceTests and its subclasses benefit from the following services provided by the Spring TestContext Framework: + *

+ *
    + *
  • Spring IoC container caching which spares us unnecessary set up time between test execution.
  • + *
  • Dependency Injection of test fixture instances, meaning that we don't need to perform application context lookups. + * See the use of {@link Autowired @Autowired} on the instance variable, which uses autowiring by type. + *
  • Transaction management, meaning each test method is executed in its own transaction, which is automatically rolled + * back by default. Thus, even if tests insert or otherwise change database state, there is no need for a teardown or cleanup script. + *
  • An {@link org.springframework.context.ApplicationContext ApplicationContext} is also inherited and can be used for explicit bean + * lookup if necessary.
  • + *
* * @author Ken Krebs * @author Rod Johnson @@ -50,137 +58,136 @@ */ public abstract class AbstractClinicServiceTests { - @Autowired - protected ClinicService clinicService; - - @Test - public void shouldFindSingleOwnerWithPet() { - Owner owner = this.clinicService.findOwnerById(1); - assertThat(owner.getLastName()).startsWith("Franklin"); - assertThat(owner.getPets().size()).isEqualTo(1); - } - - @Test - public void shouldReturnAllOwnersInCaseLastNameIsEmpty() { - Collection owners = this.clinicService.findAll(); - assertThat(owners).extracting("lastName").contains("Davis", "Franklin"); - } - - @Test - @Transactional - public void shouldInsertOwner() { - Collection owners = this.clinicService.findAll(); - int found = owners.size(); - - Owner owner = new Owner(); - owner.setFirstName("Sam"); - owner.setLastName("Schultz"); - owner.setAddress("4, Evans Street"); - owner.setCity("Wollongong"); - owner.setTelephone("4444444444"); - this.clinicService.saveOwner(owner); - assertThat(owner.getId().longValue()).isNotEqualTo(0); - - owners = this.clinicService.findAll(); - assertThat(owners.size()).isEqualTo(found + 1); - } - - @Test - @Transactional - public void shouldUpdateOwner() { - Owner owner = this.clinicService.findOwnerById(1); - String oldLastName = owner.getLastName(); - String newLastName = oldLastName + "X"; - - owner.setLastName(newLastName); - this.clinicService.saveOwner(owner); - - // retrieving new name from database - owner = this.clinicService.findOwnerById(1); - assertThat(owner.getLastName()).isEqualTo(newLastName); - } + @Autowired + protected ClinicService clinicService; + + @Test + public void shouldFindSingleOwnerWithPet() { + Owner owner = clinicService.findOwnerById(1); + assertThat(owner.getLastName()).startsWith("Franklin"); + assertThat(owner.getPets().size()).isEqualTo(1); + } + + @Test + public void shouldReturnAllOwnersInCaseLastNameIsEmpty() { + Collection owners = clinicService.findAll(); + assertThat(owners).extracting("lastName").contains("Davis", "Franklin"); + } + + @Test + @Transactional + public void shouldInsertOwner() { + Collection owners = clinicService.findAll(); + int found = owners.size(); + + Owner owner = new Owner(); + owner.setFirstName("Sam"); + owner.setLastName("Schultz"); + owner.setAddress("4, Evans Street"); + owner.setCity("Wollongong"); + owner.setTelephone("4444444444"); + clinicService.saveOwner(owner); + assertThat(owner.getId().longValue()).isNotEqualTo(0); + + owners = clinicService.findAll(); + assertThat(owners.size()).isEqualTo(found + 1); + } + + @Test + @Transactional + public void shouldUpdateOwner() { + Owner owner = clinicService.findOwnerById(1); + String oldLastName = owner.getLastName(); + String newLastName = oldLastName + "X"; + + owner.setLastName(newLastName); + clinicService.saveOwner(owner); + + // retrieving new name from database + owner = clinicService.findOwnerById(1); + assertThat(owner.getLastName()).isEqualTo(newLastName); + } @Test public void shouldFindPetWithCorrectId() { - Pet pet7 = this.clinicService.findPetById(7); - assertThat(pet7.getName()).startsWith("Samantha"); - assertThat(pet7.getOwner().getFirstName()).isEqualTo("Jean"); - + Pet pet7 = clinicService.findPetById(7); + assertThat(pet7.getName()).startsWith("Samantha"); + assertThat(pet7.getOwner().getFirstName()).isEqualTo("Jean"); + } @Test public void shouldFindAllPetTypes() { - Collection petTypes = this.clinicService.findPetTypes(); - - PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1); - assertThat(petType1.getName()).isEqualTo("cat"); - PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4); - assertThat(petType4.getName()).isEqualTo("snake"); + Collection petTypes = clinicService.findPetTypes(); + + PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1); + assertThat(petType1.getName()).isEqualTo("cat"); + PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4); + assertThat(petType4.getName()).isEqualTo("snake"); } @Test @Transactional public void shouldInsertPetIntoDatabaseAndGenerateId() { - Owner owner6 = this.clinicService.findOwnerById(6); - int found = owner6.getPets().size(); - - Pet pet = new Pet(); - pet.setName("bowser"); - Collection types = this.clinicService.findPetTypes(); - pet.setType(EntityUtils.getById(types, PetType.class, 2)); - pet.setBirthDate(new Date()); - owner6.addPet(pet); - assertThat(owner6.getPets().size()).isEqualTo(found + 1); - - this.clinicService.savePet(pet); - this.clinicService.saveOwner(owner6); - - owner6 = this.clinicService.findOwnerById(6); - assertThat(owner6.getPets().size()).isEqualTo(found + 1); - // checks that id has been generated - assertThat(pet.getId()).isNotNull(); + Owner owner6 = clinicService.findOwnerById(6); + int found = owner6.getPets().size(); + + Pet pet = new Pet(); + pet.setName("bowser"); + Collection types = clinicService.findPetTypes(); + pet.setType(EntityUtils.getById(types, PetType.class, 2)); + pet.setBirthDate(new Date()); + owner6.addPet(pet); + assertThat(owner6.getPets().size()).isEqualTo(found + 1); + + clinicService.savePet(pet); + clinicService.saveOwner(owner6); + + owner6 = clinicService.findOwnerById(6); + assertThat(owner6.getPets().size()).isEqualTo(found + 1); + // checks that id has been generated + assertThat(pet.getId()).isNotNull(); } @Test @Transactional public void shouldUpdatePetName() throws Exception { - Pet pet7 = this.clinicService.findPetById(7); - String oldName = pet7.getName(); - - String newName = oldName + "X"; + Pet pet7 = clinicService.findPetById(7); + String oldName = pet7.getName(); + + String newName = oldName + "X"; pet7.setName(newName); - this.clinicService.savePet(pet7); + clinicService.savePet(pet7); - pet7 = this.clinicService.findPetById(7); - assertThat(pet7.getName()).isEqualTo(newName); + pet7 = clinicService.findPetById(7); + assertThat(pet7.getName()).isEqualTo(newName); } @Test public void shouldFindVets() { - Collection vets = this.clinicService.findVets(); - - Vet vet = EntityUtils.getById(vets, Vet.class, 3); - assertThat(vet.getLastName()).isEqualTo("Douglas"); - assertThat(vet.getNrOfSpecialties()).isEqualTo(2); - assertThat(vet.getSpecialties().get(0).getName()).isEqualTo("dentistry"); - assertThat(vet.getSpecialties().get(1).getName()).isEqualTo("surgery"); + Collection vets = clinicService.findVets(); + + Vet vet = EntityUtils.getById(vets, Vet.class, 3); + assertThat(vet.getLastName()).isEqualTo("Douglas"); + assertThat(vet.getNrOfSpecialties()).isEqualTo(2); + assertThat(vet.getSpecialties().get(0).getName()).isEqualTo("dentistry"); + assertThat(vet.getSpecialties().get(1).getName()).isEqualTo("surgery"); } @Test @Transactional public void shouldAddNewVisitForPet() { - Pet pet7 = this.clinicService.findPetById(7); - int found = pet7.getVisits().size(); - Visit visit = new Visit(); - pet7.addVisit(visit); - visit.setDescription("test"); - this.clinicService.saveVisit(visit); - this.clinicService.savePet(pet7); - - pet7 = this.clinicService.findPetById(7); - assertThat(pet7.getVisits().size()).isEqualTo(found + 1); - assertThat(visit.getId()).isNotNull(); + Pet pet7 = clinicService.findPetById(7); + int found = pet7.getVisits().size(); + Visit visit = new Visit(); + pet7.addVisit(visit); + visit.setDescription("test"); + clinicService.saveVisit(visit); + clinicService.savePet(pet7); + + pet7 = clinicService.findPetById(7); + assertThat(pet7.getVisits().size()).isEqualTo(found + 1); + assertThat(visit.getId()).isNotNull(); } - } diff --git a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/PetResourceTests.java b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/PetResourceTests.java index 1171b2bc..67e38b60 100644 --- a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/PetResourceTests.java +++ b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/PetResourceTests.java @@ -1,7 +1,13 @@ package org.springframework.samples.petclinic.web; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -10,55 +16,49 @@ import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.service.ClinicService; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; -import static org.mockito.BDDMockito.given; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @WebMvcTest(PetResource.class) public class PetResourceTests { - @Autowired - private MockMvc mvc; - - @MockBean - ClinicService clinicService; + @Autowired + private MockMvc mvc; - @Test - public void shouldGetAPetInJSonFormat() throws Exception { + @MockBean + ClinicService clinicService; - Pet pet = setupPet(); + @Test + public void shouldGetAPetInJSonFormat() throws Exception { - given(clinicService.findPetById(2)).willReturn(pet); + Pet pet = setupPet(); + given(clinicService.findPetById(2)).willReturn(pet); - mvc.perform(get("/owners/2/pets/2").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json;charset=UTF-8")) - .andExpect(jsonPath("$.id").value(2)) - .andExpect(jsonPath("$.name").value("Basil")) - .andExpect(jsonPath("$.type.id").value(6)); - } + mvc.perform(get("/owners/2/pets/2").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.id").value(2)) + .andExpect(jsonPath("$.name").value("Basil")) + .andExpect(jsonPath("$.type.id").value(6)); + } - private Pet setupPet() {Owner owner = new Owner(); - owner.setFirstName("George"); - owner.setLastName("Bush"); + private Pet setupPet() { + Owner owner = new Owner(); + owner.setFirstName("George"); + owner.setLastName("Bush"); - Pet pet = new Pet(); + Pet pet = new Pet(); - pet.setName("Basil"); - pet.setId(2); + pet.setName("Basil"); + pet.setId(2); - PetType petType = new PetType(); - petType.setId(6); - pet.setType(petType); + PetType petType = new PetType(); + petType.setId(6); + pet.setType(petType); - owner.addPet(pet); - return pet; - } + owner.addPet(pet); + return pet; + } } diff --git a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/VetResourceTests.java b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/VetResourceTests.java index 895a33ea..4cbe082a 100644 --- a/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/VetResourceTests.java +++ b/spring-petclinic-server/src/test/java/org/springframework/samples/petclinic/web/VetResourceTests.java @@ -1,45 +1,44 @@ package org.springframework.samples.petclinic.web; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.samples.petclinic.model.Vet; import org.springframework.samples.petclinic.service.ClinicService; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; -import java.util.Arrays; - -import static org.mockito.BDDMockito.given; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @WebMvcTest(VetResource.class) public class VetResourceTests { - @Autowired - private MockMvc mvc; - - @MockBean - ClinicService clinicService; + @Autowired + private MockMvc mvc; - @Test - public void shouldGetAListOfVetsInJSonFormat() throws Exception { + @MockBean + ClinicService clinicService; - Vet vet = new Vet(); - vet.setId(1); + @Test + public void shouldGetAListOfVetsInJSonFormat() throws Exception { - given(clinicService.findVets()).willReturn(Arrays.asList(vet)); + Vet vet = new Vet(); + vet.setId(1); - mvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value(1)); - } + given(clinicService.findVets()).willReturn(Arrays.asList(vet)); + mvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(1)); + } } From 364aca163e5d2b303675cda4e80fd652e3198c5d Mon Sep 17 00:00:00 2001 From: xabier_aldama Date: Wed, 9 Feb 2022 12:47:18 +0100 Subject: [PATCH 2/4] Hateoas 1.4 --- pom.xml | 2 +- spring-petclinic-client/src/scripts/app.js | 4 +- .../owner-form/owner-form.controller.js | 1 + .../scripts/pet-form/pet-form.controller.js | 2 +- spring-petclinic-server/pom.xml | 12 + .../samples/petclinic/DelegateConfig.java | 60 ++++ .../samples/petclinic/web/PetResource.java | 304 ++++++++++-------- .../src/main/resources/application.properties | 2 + .../src/main/resources/templates/index.html | 3 + 9 files changed, 250 insertions(+), 140 deletions(-) create mode 100644 spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java diff --git a/pom.xml b/pom.xml index 3b92e4ec..cc91a95d 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.4.11 + 2.6.3 org.springframework.samples diff --git a/spring-petclinic-client/src/scripts/app.js b/spring-petclinic-client/src/scripts/app.js index 66db62a2..11c4df3f 100644 --- a/spring-petclinic-client/src/scripts/app.js +++ b/spring-petclinic-client/src/scripts/app.js @@ -1,7 +1,7 @@ 'use strict'; /* App Module */ var petClinicApp = angular.module('petClinicApp', [ - 'ui.router', 'infrastructure', 'layoutNav', 'layoutFooter', 'layoutWelcome', + 'ui.router', 'infrastructure', 'hdiv', 'layoutNav', 'layoutFooter', 'layoutWelcome', 'ownerList', 'ownerDetails', 'ownerForm', 'petForm', 'visits', 'vetList']); petClinicApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', function( @@ -9,7 +9,7 @@ petClinicApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider' // safari turns to be lazy sending the Cache-Control header $httpProvider.defaults.headers.common["Cache-Control"] = 'no-cache'; - $httpProvider.interceptors.push('HttpErrorHandlingInterceptor'); + //$httpProvider.interceptors.push('HttpErrorHandlingInterceptor'); $locationProvider.hashPrefix('!'); diff --git a/spring-petclinic-client/src/scripts/owner-form/owner-form.controller.js b/spring-petclinic-client/src/scripts/owner-form/owner-form.controller.js index 0d4a0ac2..4ca3a780 100644 --- a/spring-petclinic-client/src/scripts/owner-form/owner-form.controller.js +++ b/spring-petclinic-client/src/scripts/owner-form/owner-form.controller.js @@ -18,6 +18,7 @@ angular.module('ownerForm') var id = self.owner.id; if (id) { + delete self.owner.pets; $http.put('owners/' + id, self.owner).then(function () { $state.go('ownerDetails', {ownerId: ownerId}); }); diff --git a/spring-petclinic-client/src/scripts/pet-form/pet-form.controller.js b/spring-petclinic-client/src/scripts/pet-form/pet-form.controller.js index d17ea4ab..3ea3cf8d 100644 --- a/spring-petclinic-client/src/scripts/pet-form/pet-form.controller.js +++ b/spring-petclinic-client/src/scripts/pet-form/pet-form.controller.js @@ -29,7 +29,7 @@ angular.module('petForm') }); self.submit = function () { - var id = self.pet.id || 0; + var id = self.pet.id || undefined; var data = { id: id, diff --git a/spring-petclinic-server/pom.xml b/spring-petclinic-server/pom.xml index 4866fed8..149befc1 100644 --- a/spring-petclinic-server/pom.xml +++ b/spring-petclinic-server/pom.xml @@ -84,6 +84,11 @@ org.ehcache ehcache
+ + com.hdivsecurity + hdiv-for-services + 2.6.3 + @@ -94,6 +99,13 @@ spring-boot-maven-plugin true + + -Dhdiv.config.dir=../../config + -Dhdiv.server.name=petclinic-server + -Dhdiv.console.token=6a367E2eb97db59020a47340 + -Dhdiv.console.url="http://localhost:8180/hdiv-console-services" + -Dhdiv.root.app.name=petclinic-app + diff --git a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java new file mode 100644 index 00000000..fde28fec --- /dev/null +++ b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java @@ -0,0 +1,60 @@ +package org.springframework.samples.petclinic; + +import org.hdiv.config.annotation.ExclusionRegistry; +import org.hdiv.ee.config.annotation.ValidationConfigurer; +import org.hdiv.filter.ValidatorFilter; +import org.hdiv.listener.InitListener; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.hdivsecurity.services.config.EnableHdiv4ServicesSecurityConfiguration; +import com.hdivsecurity.services.config.HdivServicesSecurityConfigurerAdapter; +import com.hdivsecurity.services.config.ServicesSecurityConfigBuilder; + +@Configuration +@EnableHdiv4ServicesSecurityConfiguration +public class DelegateConfig extends HdivServicesSecurityConfigurerAdapter { + @Bean + // Register the Validator Filter + public FilterRegistrationBean filterRegistrationBean() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean(); + ValidatorFilter validatorFilter = new ValidatorFilter(); + registrationBean.setFilter(validatorFilter); + registrationBean.setOrder(0); + return registrationBean; + } + + @Bean + // Register the listener + public InitListener initListener() { + return new InitListener(); + } + + @Override + // Add default editable validation rules for all urls + public void configureEditableValidation(final ValidationConfigurer validationConfigurer) { + validationConfigurer.addValidation("/.*"); + } + + @Override + // Validation configuration + public void configure(final ServicesSecurityConfigBuilder builder) { + builder.confidentiality(false).sessionExpired().homePage("/"); + builder.showErrorPageOnEditableValidation(true); + builder.hypermediaSupport(false); + builder.appName("spring-petclinic-angularjs"); + + // Dashboard credentials + builder.dashboardUser("admin"); + builder.dashboardPass("hdiv"); + } + + @Override + // UI resources should be excluded + public void addExclusions(final ExclusionRegistry registry) { + registry.addUrlExclusions("/", + "/scripts/.*", "/bootstrap/.*", "/images/.*", "/fonts/.*", + "/angular-ui-router/.*", "/angular/.*", "/jquery/.*", "/css/.*"); + } +} \ No newline at end of file diff --git a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java index a7a28534..e65dbb7c 100644 --- a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java +++ b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java @@ -15,7 +15,13 @@ */ package org.springframework.samples.petclinic.web; -import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Collection; +import java.util.Date; + +import javax.validation.constraints.Size; + +import org.hdiv.services.SecureIdentifiable; +import org.hdiv.services.TrustAssertion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; @@ -23,13 +29,15 @@ import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.service.ClinicService; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; -import javax.validation.constraints.Size; - -import java.util.Collection; -import java.util.Date; -import java.util.Map; +import com.fasterxml.jackson.annotation.JsonFormat; /** * @author Juergen Hoeller @@ -39,134 +47,158 @@ @RestController public class PetResource extends AbstractResourceController { - private final ClinicService clinicService; - - @Autowired - public PetResource(ClinicService clinicService) { - this.clinicService = clinicService; - } - - @GetMapping("/petTypes") - Collection getPetTypes() { - return clinicService.findPetTypes(); - } - - @PostMapping("/owners/{ownerId}/pets") - @ResponseStatus(HttpStatus.NO_CONTENT) - public void processCreationForm( - @RequestBody PetRequest petRequest, - @PathVariable("ownerId") int ownerId) { - - Pet pet = new Pet(); - Owner owner = this.clinicService.findOwnerById(ownerId); - owner.addPet(pet); - - save(pet, petRequest); - } - - @PutMapping("/owners/{ownerId}/pets/{petId}") - @ResponseStatus(HttpStatus.NO_CONTENT) - public void processUpdateForm(@RequestBody PetRequest petRequest) { - save(clinicService.findPetById(petRequest.getId()), petRequest); - } - - private void save(Pet pet, PetRequest petRequest) { - - pet.setName(petRequest.getName()); - pet.setBirthDate(petRequest.getBirthDate()); - - for (PetType petType : clinicService.findPetTypes()) { - if (petType.getId() == petRequest.getTypeId()) { - pet.setType(petType); - } - } - - clinicService.savePet(pet); - } - - @GetMapping("/owners/*/pets/{petId}") - public PetDetails findPet(@PathVariable("petId") int petId) { - Pet pet = this.clinicService.findPetById(petId); - return new PetDetails(pet); - } - - static class PetRequest { - int id; - @JsonFormat(pattern = "yyyy-MM-dd") - Date birthDate; - @Size(min = 1) - String name; - int typeId; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public Date getBirthDate() { - return birthDate; - } - - public void setBirthDate(Date birthDate) { - this.birthDate = birthDate; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getTypeId() { - return typeId; - } - - public void setTypeId(int typeId) { - this.typeId = typeId; - } - } - - static class PetDetails { - - int id; - String name; - String owner; - @DateTimeFormat(pattern = "yyyy-MM-dd") - Date birthDate; - PetType type; - - PetDetails(Pet pet) { - this.id = pet.getId(); - this.name = pet.getName(); - this.owner = pet.getOwner().getFirstName() + " " + pet.getOwner().getLastName(); - this.birthDate = pet.getBirthDate(); - this.type = pet.getType(); - } - - public int getId() { - return id; - } - - public String getName() { - return name; - } - - public String getOwner() { - return owner; - } - - public Date getBirthDate() { - return birthDate; - } - - public PetType getType() { - return type; - } - } + private final ClinicService clinicService; + + @Autowired + public PetResource(final ClinicService clinicService) { + this.clinicService = clinicService; + } + + @GetMapping("/petTypes") + Collection getPetTypes() { + return clinicService.findPetTypes(); + } + + @PostMapping("/owners/{ownerId}/pets") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void processCreationForm( + @RequestBody final PetRequest petRequest, + @PathVariable("ownerId") final int ownerId) { + + Pet pet = new Pet(); + Owner owner = clinicService.findOwnerById(ownerId); + owner.addPet(pet); + + save(pet, petRequest); + } + + @PutMapping("/owners/{ownerId}/pets/{petId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void processUpdateForm(@RequestBody final PetRequest petRequest) { + save(clinicService.findPetById(petRequest.getId()), petRequest); + } + + private void save(final Pet pet, final PetRequest petRequest) { + + pet.setName(petRequest.getName()); + pet.setBirthDate(petRequest.getBirthDate()); + + for (PetType petType : clinicService.findPetTypes()) { + if (petType.getId() == petRequest.getTypeId()) { + pet.setType(petType); + } + } + + clinicService.savePet(pet); + } + + @GetMapping("/owners/*/pets/{petId}") + public PetDetails findPet(@PathVariable("petId") final int petId) { + Pet pet = clinicService.findPetById(petId); + return new PetDetails(pet); + } + + static class PetRequest implements SecureIdentifiable { + + @TrustAssertion(idFor = Pet.class) + private int id; + + @Override + public Integer getId() { + return id; + } + + @JsonFormat(pattern = "yyyy-MM-dd") + Date birthDate; + + @Size(min = 1) + String name; + + @TrustAssertion(idFor = PetType.class) + int typeId; + + public void setId(final int id) { + this.id = id; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(final Date birthDate) { + this.birthDate = birthDate; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public int getTypeId() { + return typeId; + } + + public void setTypeId(final int typeId) { + this.typeId = typeId; + } + } + + static class PetDetails implements SecureIdentifiable { + @TrustAssertion(idFor = Pet.class) + private int id; + + @Override + public Integer getId() { + return id; + } + + String name; + + String owner; + + @DateTimeFormat(pattern = "yyyy-MM-dd") + Date birthDate; + + PetType type; + + PetDetails() { + } + + PetDetails(final Pet pet) { + id = pet.getId(); + name = pet.getName(); + owner = pet.getOwner().getFirstName() + " " + pet.getOwner().getLastName(); + birthDate = pet.getBirthDate(); + type = pet.getType(); + } + + public PetRequest map(final Class destinationClass) { + PetRequest request = new PetRequest(); + request.setId(id); + request.setBirthDate(birthDate); + request.setName(name); + request.setTypeId(type.getId()); + return request; + } + + public String getName() { + return name; + } + + public String getOwner() { + return owner; + } + + public Date getBirthDate() { + return birthDate; + } + + public PetType getType() { + return type; + } + } } diff --git a/spring-petclinic-server/src/main/resources/application.properties b/spring-petclinic-server/src/main/resources/application.properties index 19e18c19..5051ee11 100644 --- a/spring-petclinic-server/src/main/resources/application.properties +++ b/spring-petclinic-server/src/main/resources/application.properties @@ -24,3 +24,5 @@ spring.profiles.active=prod server.compression.enabled=true server.compression.mime-types=application/json,text/css,application/javascript server.compression.min-response-size=2048 +spring.main.allow-circular-references=true +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER \ No newline at end of file diff --git a/spring-petclinic-server/src/main/resources/templates/index.html b/spring-petclinic-server/src/main/resources/templates/index.html index facc824c..41a10b86 100644 --- a/spring-petclinic-server/src/main/resources/templates/index.html +++ b/spring-petclinic-server/src/main/resources/templates/index.html @@ -20,6 +20,9 @@ + + + From e5f81ffcf41719f449620d86e401d63c9a8400a6 Mon Sep 17 00:00:00 2001 From: xabier_aldama Date: Wed, 9 Feb 2022 12:59:21 +0100 Subject: [PATCH 3/4] DEleted unnecesary dependency --- spring-petclinic-server/pom.xml | 5 -- .../samples/petclinic/DelegateConfig.java | 60 ------------------- .../samples/petclinic/web/PetResource.java | 11 +--- 3 files changed, 2 insertions(+), 74 deletions(-) delete mode 100644 spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java diff --git a/spring-petclinic-server/pom.xml b/spring-petclinic-server/pom.xml index 149befc1..b27d9142 100644 --- a/spring-petclinic-server/pom.xml +++ b/spring-petclinic-server/pom.xml @@ -84,11 +84,6 @@ org.ehcache ehcache - - com.hdivsecurity - hdiv-for-services - 2.6.3 - diff --git a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java deleted file mode 100644 index fde28fec..00000000 --- a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/DelegateConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.springframework.samples.petclinic; - -import org.hdiv.config.annotation.ExclusionRegistry; -import org.hdiv.ee.config.annotation.ValidationConfigurer; -import org.hdiv.filter.ValidatorFilter; -import org.hdiv.listener.InitListener; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.hdivsecurity.services.config.EnableHdiv4ServicesSecurityConfiguration; -import com.hdivsecurity.services.config.HdivServicesSecurityConfigurerAdapter; -import com.hdivsecurity.services.config.ServicesSecurityConfigBuilder; - -@Configuration -@EnableHdiv4ServicesSecurityConfiguration -public class DelegateConfig extends HdivServicesSecurityConfigurerAdapter { - @Bean - // Register the Validator Filter - public FilterRegistrationBean filterRegistrationBean() { - FilterRegistrationBean registrationBean = new FilterRegistrationBean(); - ValidatorFilter validatorFilter = new ValidatorFilter(); - registrationBean.setFilter(validatorFilter); - registrationBean.setOrder(0); - return registrationBean; - } - - @Bean - // Register the listener - public InitListener initListener() { - return new InitListener(); - } - - @Override - // Add default editable validation rules for all urls - public void configureEditableValidation(final ValidationConfigurer validationConfigurer) { - validationConfigurer.addValidation("/.*"); - } - - @Override - // Validation configuration - public void configure(final ServicesSecurityConfigBuilder builder) { - builder.confidentiality(false).sessionExpired().homePage("/"); - builder.showErrorPageOnEditableValidation(true); - builder.hypermediaSupport(false); - builder.appName("spring-petclinic-angularjs"); - - // Dashboard credentials - builder.dashboardUser("admin"); - builder.dashboardPass("hdiv"); - } - - @Override - // UI resources should be excluded - public void addExclusions(final ExclusionRegistry registry) { - registry.addUrlExclusions("/", - "/scripts/.*", "/bootstrap/.*", "/images/.*", "/fonts/.*", - "/angular-ui-router/.*", "/angular/.*", "/jquery/.*", "/css/.*"); - } -} \ No newline at end of file diff --git a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java index e65dbb7c..09780fb7 100644 --- a/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java +++ b/spring-petclinic-server/src/main/java/org/springframework/samples/petclinic/web/PetResource.java @@ -20,8 +20,6 @@ import javax.validation.constraints.Size; -import org.hdiv.services.SecureIdentifiable; -import org.hdiv.services.TrustAssertion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; @@ -98,12 +96,10 @@ public PetDetails findPet(@PathVariable("petId") final int petId) { return new PetDetails(pet); } - static class PetRequest implements SecureIdentifiable { + static class PetRequest { - @TrustAssertion(idFor = Pet.class) private int id; - @Override public Integer getId() { return id; } @@ -114,7 +110,6 @@ public Integer getId() { @Size(min = 1) String name; - @TrustAssertion(idFor = PetType.class) int typeId; public void setId(final int id) { @@ -146,11 +141,9 @@ public void setTypeId(final int typeId) { } } - static class PetDetails implements SecureIdentifiable { - @TrustAssertion(idFor = Pet.class) + static class PetDetails { private int id; - @Override public Integer getId() { return id; } From 3b13e8efb5737ee25e752b40bb7aac7a638b0046 Mon Sep 17 00:00:00 2001 From: xabier_aldama Date: Wed, 9 Feb 2022 13:06:03 +0100 Subject: [PATCH 4/4] Deleted spring.main.allow-circular-references flag from properties --- .../src/main/resources/application.properties | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/spring-petclinic-server/src/main/resources/application.properties b/spring-petclinic-server/src/main/resources/application.properties index 5051ee11..debac024 100644 --- a/spring-petclinic-server/src/main/resources/application.properties +++ b/spring-petclinic-server/src/main/resources/application.properties @@ -23,6 +23,4 @@ spring.profiles.active=prod server.compression.enabled=true server.compression.mime-types=application/json,text/css,application/javascript -server.compression.min-response-size=2048 -spring.main.allow-circular-references=true -spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER \ No newline at end of file +server.compression.min-response-size=2048 \ No newline at end of file