overall cleanup

Signed-off-by: Alireza <>
This commit is contained in:
Alireza 2023-10-14 20:50:30 +02:00 committed by Alireza
parent 923e2b7aa3
commit ee7f64bcb1
55 changed files with 731 additions and 9033 deletions

31
pom.xml
View file

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-petclinic</artifactId>
@ -32,6 +33,8 @@
<maven-checkstyle.version>3.2.2</maven-checkstyle.version>
<nohttp-checkstyle.version>0.0.11</nohttp-checkstyle.version>
<spring-format.version>0.0.39</spring-format.version>
<lombok.version>1.18.20</lombok.version>
<apache-lang3.version>3.12.0</apache-lang3.version>
</properties>
@ -138,6 +141,19 @@
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
@ -166,7 +182,8 @@
<configuration>
<rules>
<requireJavaVersion>
<message>This build requires at least Java ${java.version}, update your JVM, and run the build again</message>
<message>This build requires at least Java ${java.version}, update your JVM, and run the build again
</message>
<version>${java.version}</version>
</requireJavaVersion>
</rules>
@ -370,7 +387,9 @@
<configuration>
<inputPath>${basedir}/src/main/scss/</inputPath>
<outputPath>${basedir}/src/main/resources/static/resources/css/</outputPath>
<includePath>${project.build.directory}/webjars/META-INF/resources/webjars/bootstrap/${webjars-bootstrap.version}/scss/</includePath>
<includePath>
${project.build.directory}/webjars/META-INF/resources/webjars/bootstrap/${webjars-bootstrap.version}/scss/
</includePath>
</configuration>
</plugin>
</plugins>
@ -405,7 +424,7 @@
</goals>
</pluginExecutionFilter>
<action>
<ignore />
<ignore/>
</action>
</pluginExecution>
<pluginExecution>
@ -418,7 +437,7 @@
</goals>
</pluginExecutionFilter>
<action>
<ignore />
<ignore/>
</action>
</pluginExecution>
<pluginExecution>
@ -431,7 +450,7 @@
</goals>
</pluginExecutionFilter>
<action>
<ignore />
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>

View file

@ -17,6 +17,9 @@ git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
./mvnw package
java -jar target/*.jar
Extras:
Also ,,enable annotation processing" in `Compiler > Annotation Processors` so that you can work with lombok properly
```
You can then access petclinic at http://localhost:8080/
@ -84,7 +87,12 @@ At development time we recommend you use the test applications set up as `main()
## Compiling the CSS
There is a `petclinic.css` in `src/main/resources/static/resources/css`. It was generated from the `petclinic.scss` source, combined with the [Bootstrap](https://getbootstrap.com/) library. If you make changes to the `scss`, or upgrade Bootstrap, you will need to re-compile the CSS resources using the Maven profile "css", i.e. `./mvnw package -P css`. There is no build profile for Gradle to compile the CSS.
There is a `petclinic.css` in `src/main/resources/static/resources/css`.
It was generated from the `petclinic.scss` source, combined with the [Bootstrap](https://getbootstrap.com/) library.
If you make changes to the `scss`, or upgrade Bootstrap, you will need to re-compile the CSS resources using the Maven profile "css", i.e. `./mvnw package -P css`.
There is no build profile for Gradle to compile the CSS.
In case you have changes that are already inside `petclinic.scss` e.g use of bootstrap classes that are already included, there is no need to do the steps.
## Working with Petclinic in your IDE

View file

@ -0,0 +1,13 @@
package Utils;
import org.springframework.lang.Nullable;
import java.util.Collection;
public class CollectionUtils {
public static boolean isEmpty(@Nullable Collection<?> collection) {
return collection == null || collection.isEmpty();
}
}

View file

@ -13,13 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import java.time.LocalDate;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.samples.petclinic.model.NamedEntity;
@ -32,6 +35,7 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import org.springframework.samples.petclinic.owner.Visit;
/**
* Simple business object representing a pet.
@ -41,6 +45,8 @@ import jakarta.persistence.Table;
* @author Sam Brannen
*/
@Entity
@Getter
@Setter
@Table(name = "pets")
public class Pet extends NamedEntity {
@ -52,33 +58,14 @@ public class Pet extends NamedEntity {
@JoinColumn(name = "type_id")
private PetType type;
@Setter(AccessLevel.NONE)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "pet_id")
@OrderBy("visit_date ASC")
private Set<Visit> visits = new LinkedHashSet<>();
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public LocalDate getBirthDate() {
return this.birthDate;
}
public PetType getType() {
return this.type;
}
public void setType(PetType type) {
this.type = type;
}
public Collection<Visit> getVisits() {
return this.visits;
}
public void addVisit(Visit visit) {
getVisits().add(visit);
this.visits.add(visit);
}
}

View file

@ -13,14 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import java.time.LocalDate;
import java.util.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.samples.petclinic.Validation.PetDataBinderValidator;
import org.springframework.samples.petclinic.Validation.InputValidator;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.OwnerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
@ -39,39 +42,29 @@ import jakarta.validation.Valid;
*/
@Controller
@RequestMapping("/owners/{ownerId}")
@RequiredArgsConstructor
class PetController {
private static final String VIEWS_PETS_CREATE_OR_UPDATE_FORM = "pets/createOrUpdatePetForm";
private final OwnerRepository owners;
private final OwnerService ownerService;
public PetController(OwnerRepository owners) {
this.owners = owners;
}
private final InputValidator inputValidator;
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.owners.findPetTypes();
return this.ownerService.findPetTypes();
}
@ModelAttribute("owner")
public Owner findOwner(@PathVariable("ownerId") int ownerId) {
Owner owner = this.owners.findById(ownerId);
if (owner == null) {
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
}
return owner;
return ownerService.findOwner(ownerId);
}
@ModelAttribute("pet")
public Pet findPet(@PathVariable("ownerId") int ownerId,
@PathVariable(name = "petId", required = false) Integer petId) {
Owner owner = this.owners.findById(ownerId);
if (owner == null) {
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
}
var owner = ownerService.findOwner(ownerId);
return petId == null ? new Pet() : owner.getPet(petId);
}
@ -82,7 +75,7 @@ class PetController {
@InitBinder("pet")
public void initPetBinder(WebDataBinder dataBinder) {
dataBinder.setValidator(new PetValidator());
dataBinder.setValidator(new PetDataBinderValidator());
}
@GetMapping("/pets/new")
@ -95,14 +88,9 @@ class PetController {
@PostMapping("/pets/new")
public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) {
if (StringUtils.hasText(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null) {
result.rejectValue("name", "duplicate", "already exists");
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
this.inputValidator.validatePetDuplication(result, pet, owner);
this.inputValidator.validateDate(result, pet, "birthDate");
owner.addPet(pet);
if (result.hasErrors()) {
@ -110,7 +98,7 @@ class PetController {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
this.owners.save(owner);
this.ownerService.saveOwner(owner);
return "redirect:/owners/{ownerId}";
}
@ -123,21 +111,8 @@ class PetController {
@PostMapping("/pets/{petId}/edit")
public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) {
String petName = pet.getName();
// checking if the pet name already exist for the owner
if (StringUtils.hasText(petName)) {
Pet existingPet = owner.getPet(petName.toLowerCase(), false);
if (existingPet != null && existingPet.getId() != pet.getId()) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
this.inputValidator.validatePetUpdateDuplication(result, pet, owner);
this.inputValidator.validateDate(result, pet, "birthDate");
if (result.hasErrors()) {
model.put("pet", pet);
@ -145,7 +120,7 @@ class PetController {
}
owner.addPet(pet);
this.owners.save(owner);
this.ownerService.saveOwner(owner);
return "redirect:/owners/{ownerId}";
}

View file

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.model.NamedEntity;

View file

@ -13,14 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.Formatter;
import org.springframework.samples.petclinic.owner.OwnerRepository;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
/**
@ -34,29 +36,25 @@ import java.util.Locale;
* @author Michael Isvy
*/
@Component
@RequiredArgsConstructor
public class PetTypeFormatter implements Formatter<PetType> {
private final OwnerRepository owners;
@Autowired
public PetTypeFormatter(OwnerRepository owners) {
this.owners = owners;
}
@Override
public String print(PetType petType, Locale locale) {
return petType.getName();
}
// text = toString of PetType
@Override
public PetType parse(String text, Locale locale) throws ParseException {
Collection<PetType> findPetTypes = this.owners.findPetTypes();
for (PetType type : findPetTypes) {
if (type.getName().equals(text)) {
return type;
}
}
throw new ParseException("type not found: " + text, 0);
List<PetType> petTypes = this.owners.findPetTypes();
return petTypes.stream()
.filter(petType -> StringUtils.containsIgnoreCase(text, petType.getName()))
.findFirst()
.orElseThrow(() -> new ParseException("type not found: " + text, 0));
}
}

View file

@ -0,0 +1,28 @@
package org.springframework.samples.petclinic.Pet;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Getter
@RequiredArgsConstructor
public enum PetTypes {
CAT("cat", "pet.cat"), DOG("dog", "pet.dog"), LIZARD("lizard", "pet.lizard"), SNAKE("snake", "pet.snake"),
BIRD("bird", "pet.bird"), HAMSTER("hamster", "pet.hamster");
private final String value;
private final String frontendTranslationKey;
// TODO: Refactor so we will use this instead of taking all Types from db
public static List<String> getPetTypeNames() {
List<String> allPetTypeNames = new ArrayList<>();
Arrays.stream(values()).map(PetTypes::getValue).forEach(petTypesName -> allPetTypeNames.add(petTypesName));
return allPetTypeNames;
}
}

View file

@ -30,6 +30,7 @@ public class PetClinicRuntimeHints implements RuntimeHintsRegistrar {
hints.resources().registerPattern("messages/*");
hints.resources().registerPattern("META-INF/resources/webjars/*");
hints.resources().registerPattern("mysql-default-conf");
hints.serialization().registerType(BaseEntity.class);
hints.serialization().registerType(Person.class);
hints.serialization().registerType(Vet.class);

View file

@ -0,0 +1,70 @@
package org.springframework.samples.petclinic.Validation;
import jakarta.validation.constraints.NotNull;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.Visit;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import java.time.LocalDate;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
@Component
public class InputValidator {
public void validatePetDuplication(BindingResult result, Pet pet, Owner owner) {
requireNonNull(pet, "pet is null");
requireNonNull(pet, "owner is null");
boolean ownerHasExistingPet = owner.getPet(pet.getName(), true) != null;
if (StringUtils.hasText(pet.getName()) && pet.isNewEntry() && ownerHasExistingPet) {
result.rejectValue("name", "duplicate");
}
}
public void validatePetUpdateDuplication(BindingResult result, Pet pet, Owner owner) {
requireNonNull(pet, "pet is null");
requireNonNull(pet, "owner is null");
var ownerHasExistingPet = owner.getPet(pet.getName(), false);
var notSameId = !Objects.equals(ownerHasExistingPet.getId(), pet.getId());
if (StringUtils.hasText(pet.getName()) && ownerHasExistingPet != null && notSameId) {
result.rejectValue("name", "duplicate");
}
}
public <T> void validateDate(BindingResult result, @NotNull T obj, String fieldName) {
requireNonNull(obj, "pet is null");
// Refactor in case of changing to higher Java versions > 17 to use switch pattern
// matching
LocalDate date = null;
if (obj instanceof Pet pet) {
date = pet.getBirthDate();
}
else if (obj instanceof Visit visit) {
date = visit.getDate();
}
if (date == null) {
result.rejectValue(fieldName, "typeMismatch.birthDate");
}
else if (date.isAfter(LocalDate.now())) {
result.rejectValue(fieldName, "typeMismatch.birthDate.future");
}
}
public void validateString(BindingResult result, @NotNull Visit visit, String fieldName) {
if (!StringUtils.hasText(visit.getDescription())) {
result.rejectValue(fieldName, "required");
}
}
}

View file

@ -13,8 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Validation;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@ -29,7 +30,7 @@ import org.springframework.validation.Validator;
* @author Ken Krebs
* @author Juergen Hoeller
*/
public class PetValidator implements Validator {
public class PetDataBinderValidator implements Validator {
private static final String REQUIRED = "required";
@ -42,12 +43,10 @@ public class PetValidator implements Validator {
errors.rejectValue("name", REQUIRED, REQUIRED);
}
// type validation
if (pet.isNew() && pet.getType() == null) {
if (pet.isNewEntry() && pet.getType() == null) {
errors.rejectValue("type", REQUIRED, REQUIRED);
}
// birth date validation
if (pet.getBirthDate() == null) {
errors.rejectValue("birthDate", REQUIRED, REQUIRED);
}

View file

@ -21,6 +21,8 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import lombok.Setter;
/**
* Simple JavaBean domain object with an id property. Used as a base class for objects
@ -29,6 +31,9 @@ import jakarta.persistence.MappedSuperclass;
* @author Ken Krebs
* @author Juergen Hoeller
*/
@Getter
@Setter
@MappedSuperclass
public class BaseEntity implements Serializable {
@ -36,15 +41,7 @@ public class BaseEntity implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isNew() {
public boolean isNewEntry() {
return this.id == null;
}

View file

@ -17,6 +17,7 @@ package org.springframework.samples.petclinic.model;
import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;
import lombok.*;
/**
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>. Used as
@ -26,19 +27,14 @@ import jakarta.persistence.MappedSuperclass;
* @author Juergen Hoeller
*/
@MappedSuperclass
@Getter
@Setter
public class NamedEntity extends BaseEntity {
@Column(name = "name")
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// PetTypeFormatter#parse
@Override
public String toString() {
return this.getName();

View file

@ -18,6 +18,12 @@ package org.springframework.samples.petclinic.model;
import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.builder.EqualsBuilder;
import java.util.Objects;
/**
* Simple JavaBean domain object representing an person.
@ -25,6 +31,9 @@ import jakarta.validation.constraints.NotBlank;
* @author Ken Krebs
*/
@MappedSuperclass
@Getter
@Setter
@ToString
public class Person extends BaseEntity {
@Column(name = "first_name")
@ -35,20 +44,24 @@ public class Person extends BaseEntity {
@NotBlank
private String lastName;
public String getFirstName() {
return this.firstName;
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
Person person = (Person) object;
return new EqualsBuilder().append(firstName, person.firstName)
.append(lastName, person.lastName)
.append(super.getId(), person.getId())
.isEquals();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}

View file

@ -15,12 +15,14 @@
*/
package org.springframework.samples.petclinic.owner;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import Utils.CollectionUtils;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.style.ToStringCreator;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.model.Person;
import org.springframework.util.Assert;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
@ -33,6 +35,8 @@ import jakarta.persistence.Table;
import jakarta.validation.constraints.Digits;
import jakarta.validation.constraints.NotBlank;
import static java.util.function.Predicate.not;
/**
* Simple JavaBean domain object representing an owner.
*
@ -44,6 +48,8 @@ import jakarta.validation.constraints.NotBlank;
*/
@Entity
@Table(name = "owners")
@Getter
@Setter
public class Owner extends Person {
@Column(name = "address")
@ -59,42 +65,19 @@ public class Owner extends Person {
@Digits(fraction = 0, integer = 10)
private String telephone;
@Setter(AccessLevel.NONE)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
@OrderBy("name")
private List<Pet> pets = new ArrayList<>();
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public List<Pet> getPets() {
return this.pets;
}
public void addPet(Pet pet) {
if (pet.isNew()) {
getPets().add(pet);
boolean petIsNewInList = false;
if (!CollectionUtils.isEmpty(this.pets)) {
petIsNewInList = this.pets.stream().anyMatch(value -> value.equals(pet));
}
if (pet.isNewEntry() || !petIsNewInList) {
this.pets.add(pet);
}
}
@ -109,49 +92,28 @@ public class Owner extends Person {
/**
* Return the Pet with the given id, or null if none found for this Owner.
* @param id to test
* @param petId to test
* @return a pet if pet id is already in use
*/
public Pet getPet(Integer id) {
for (Pet pet : getPets()) {
if (!pet.isNew()) {
Integer compId = pet.getId();
if (compId.equals(id)) {
return pet;
}
}
}
return null;
public Pet getPet(Integer petId) {
return this.pets.stream()
.filter(not(Pet::isNewEntry))
.filter(pet -> pet.getId().equals(petId))
.findFirst()
.orElse(null);
}
/**
* Return the Pet with the given name, or null if none found for this Owner.
* @param name to test
* @param petName to test
* @return a pet if pet name is already in use
*/
public Pet getPet(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Pet pet : getPets()) {
String compName = pet.getName();
if (compName != null && compName.equalsIgnoreCase(name)) {
if (!ignoreNew || !pet.isNew()) {
return pet;
}
}
}
return null;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
public Pet getPet(String petName, boolean ignoreNew) {
return this.pets.stream()
.filter(pet -> StringUtils.containsIgnoreCase(pet.getName(), petName))
.filter(pet -> !ignoreNew || !pet.isNewEntry())
.findFirst()
.orElse(null);
}
/**
@ -160,15 +122,20 @@ public class Owner extends Person {
* @param visit the visit to add, must not be {@literal null}.
*/
public void addVisit(Integer petId, Visit visit) {
Assert.notNull(petId, "Pet identifier must not be null!");
Assert.notNull(visit, "Visit must not be null!");
Pet pet = getPet(petId);
Assert.notNull(pet, "Invalid Pet identifier!");
Pet pet = Objects.requireNonNull(getPet(petId), "no pet found with given Id");
pet.addVisit(visit);
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", this.getId())
.append("new", this.isNewEntry())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
}
}

View file

@ -18,6 +18,7 @@ package org.springframework.samples.petclinic.owner;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@ -42,15 +43,16 @@ import jakarta.validation.Valid;
* @author Michael Isvy
*/
@Controller
@RequiredArgsConstructor
class OwnerController {
private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm";
private final OwnerRepository owners;
private static final int PAGE_SIZE = 5;
public OwnerController(OwnerRepository clinicService) {
this.owners = clinicService;
}
private final OwnerService ownerService;
private final OwnerRepository owners;
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
@ -59,7 +61,7 @@ class OwnerController {
@ModelAttribute("owner")
public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) {
return ownerId == null ? new Owner() : this.owners.findById(ownerId);
return ownerId == null ? new Owner() : ownerService.findOwner(ownerId);
}
@GetMapping("/owners/new")
@ -120,14 +122,13 @@ class OwnerController {
}
private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) {
int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
Pageable pageable = PageRequest.of(page - 1, PAGE_SIZE);
return owners.findByLastName(lastname, pageable);
}
@GetMapping("/owners/{ownerId}/edit")
public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
Owner owner = this.owners.findById(ownerId);
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute(owner);
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
}
@ -152,7 +153,7 @@ class OwnerController {
@GetMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails");
Owner owner = this.owners.findById(ownerId);
Owner owner = ownerService.findOwner(ownerId);
mav.addObject(owner);
return mav;
}

View file

@ -22,6 +22,7 @@ import org.springframework.data.domain.Pageable;
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.Pet.PetType;
import org.springframework.transaction.annotation.Transactional;
/**

View file

@ -0,0 +1,32 @@
package org.springframework.samples.petclinic.owner;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.samples.petclinic.Pet.PetType;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;
@Service
@RequiredArgsConstructor
public class OwnerService {
private final OwnerRepository owners;
public Owner findOwner(Integer ownerId) {
Owner owner = this.owners.findById(ownerId);
Assert.notNull(owner, "Owner ID not found: " + ownerId);
return owner;
}
public List<PetType> findPetTypes() {
return this.owners.findPetTypes();
}
public void saveOwner(@NotNull Owner owner) {
// add fancy logic here to make this method more useful
this.owners.save(owner);
}
}

View file

@ -17,6 +17,9 @@ package org.springframework.samples.petclinic.owner;
import java.time.LocalDate;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.samples.petclinic.model.BaseEntity;
@ -33,36 +36,19 @@ import jakarta.validation.constraints.NotBlank;
*/
@Entity
@Table(name = "visits")
@Getter
@Setter
public class Visit extends BaseEntity {
@Column(name = "visit_date")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
@NotBlank
@NotNull
private String description;
/**
* Creates a new instance of Visit for the current date
*/
public Visit() {
this.date = LocalDate.now();
}
public LocalDate getDate() {
return this.date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}

View file

@ -17,14 +17,14 @@ package org.springframework.samples.petclinic.owner;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.Validation.InputValidator;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
@ -36,13 +36,12 @@ import jakarta.validation.Valid;
* @author Dave Syer
*/
@Controller
@RequiredArgsConstructor
class VisitController {
private final OwnerRepository owners;
public VisitController(OwnerRepository owners) {
this.owners = owners;
}
private final InputValidator inputValidator;
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
@ -82,12 +81,19 @@ class VisitController {
@PostMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit,
BindingResult result) {
Assert.notNull(petId, "Pet identifier must not be null!");
Assert.notNull(visit, "Visit must not be null!");
this.inputValidator.validateDate(result, visit, "date");
this.inputValidator.validateString(result, visit, "description");
if (result.hasErrors()) {
return "pets/createOrUpdateVisitForm";
}
owner.addVisit(petId, visit);
this.owners.save(owner);
return "redirect:/owners/{ownerId}";
}

View file

@ -57,10 +57,6 @@ public class Vet extends Person {
return this.specialties;
}
protected void setSpecialtiesInternal(Set<Specialty> specialties) {
this.specialties = specialties;
}
@XmlElement
public List<Specialty> getSpecialties() {
List<Specialty> sortedSpecs = new ArrayList<>(getSpecialtiesInternal());

View file

@ -17,6 +17,7 @@ package org.springframework.samples.petclinic.vet;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@ -33,21 +34,20 @@ import org.springframework.web.bind.annotation.ResponseBody;
* @author Arjen Poutsma
*/
@Controller
@RequiredArgsConstructor
class VetController {
private final VetRepository vetRepository;
public VetController(VetRepository clinicService) {
this.vetRepository = clinicService;
}
@GetMapping("/vets.html")
public String showVetList(@RequestParam(defaultValue = "1") int page, Model model) {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for Object-Xml mapping
Vets vets = new Vets();
Page<Vet> paginated = findPaginated(page);
vets.getVetList().addAll(paginated.toList());
return addPaginationModel(page, paginated, model);
}
@ -60,18 +60,20 @@ class VetController {
return "vets/vetList";
}
private Page<Vet> findPaginated(int page) {
private Page<Vet> findPaginated(int currentPageNumber) {
int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
Pageable pageable = PageRequest.of(currentPageNumber - 1, pageSize);
return vetRepository.findAll(pageable);
}
@GetMapping({ "/vets" })
public @ResponseBody Vets showResourcesVetList() {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for JSon/Object mapping
Vets vets = new Vets();
vets.getVetList().addAll(this.vetRepository.findAll());
return vets;
}

View file

@ -1,3 +1,4 @@
# database init
database=postgres
spring.datasource.url=${POSTGRES_URL:jdbc:postgresql://localhost/petclinic}
spring.datasource.username=${POSTGRES_USER:petclinic}

View file

@ -21,5 +21,9 @@ logging.level.org.springframework=INFO
# logging.level.org.springframework.web=DEBUG
# logging.level.org.springframework.context.annotation=TRACE
# SQL Logging
# spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# Maximum time static resources should be cached
spring.web.resources.cache.cachecontrol.max-age=12h

View file

@ -1,8 +1,9 @@
welcome=Welcome
required=is required
notFound=has not been found
duplicate=is already in use
duplication=is already in use
nonNumeric=must be all numeric
duplicateFormSubmission=Duplicate form submission is not allowed
typeMismatch.date=invalid date
typeMismatch.birthDate=invalid date
typeMismatch.birthDate=empty date
typeMismatch.birthDate.future=date is in the future

View file

@ -4,6 +4,7 @@ notFound=wurde nicht gefunden
duplicate=ist bereits vergeben
nonNumeric=darf nur numerisch sein
duplicateFormSubmission=Wiederholtes Absenden des Formulars ist nicht erlaubt
typeMismatch.date=ung<EFBFBD>ltiges Datum
typeMismatch.birthDate=ung<EFBFBD>ltiges Datum
typeMismatch.date=ungültiges Datum
typeMismatch.birthDate=leeres Datum
typeMismatch.birthDate.future=Das Datum liegt in der Zukunft

View file

@ -5,5 +5,5 @@ duplicate=Ya se encuentra en uso
nonNumeric=Sólo debe contener numeros
duplicateFormSubmission=No se permite el envío de formularios duplicados
typeMismatch.date=Fecha invalida
typeMismatch.birthDate=Fecha invalida
typeMismatch.birthDate=fecha vacía
typeMismatch.birthDate.future=la fecha es en el futuro

View file

@ -5,4 +5,5 @@ duplicate=이미 존재합니다
nonNumeric=모두 숫자로 입력해야 합니다
duplicateFormSubmission=중복 제출은 허용되지 않습니다
typeMismatch.date=잘못된 날짜입니다
typeMismatch.birthDate=잘못된 날짜입니다
typeMismatch.birthDate=잘못된 날짜입니다 //TODO change to: empty date
typeMismatch.birthDate.future=date is in the future

File diff suppressed because it is too large Load diff

View file

@ -5,19 +5,20 @@
<div th:with="valid=${!#fields.hasErrors(name)}"
th:class="${'form-group' + (valid ? '' : ' has-error')}"
class="form-group">
<label class="col-sm-2 control-label" th:text="${label}">Label</label>
<div class="col-sm-10">
<label class="col-sm-2 control-label asterisk" th:text="${label}">Label</label>
<div class="col-sm-5 mb-3">
<div th:switch="${type}">
<input th:case="'text'" class="form-control" type="text" th:field="*{__${name}__}" />
<input th:case="'date'" class="form-control" type="date" th:field="*{__${name}__}"/>
</div>
<span th:if="${valid}"
class="fa fa-ok form-control-feedback"
aria-hidden="true"></span>
aria-hidden="true">
</span>
<th:block th:if="${!valid}">
<span
class="fa fa-remove form-control-feedback"
aria-hidden="true"></span>
class="fa fa-remove form-control-feedback mb-4"
aria-hidden="true"/>
<span class="help-inline" th:errors="*{__${name}__}">Error</span>
</th:block>
</div>

View file

@ -80,7 +80,12 @@
<div class="container">
<div class="row">
<div class="col-12 text-center">
<img src="../static/images/spring-logo.svg" th:src="@{/resources/images/spring-logo.svg}" alt="VMware Tanzu Logo" class="logo">
<img
src="../static/images/spring-logo.svg"
th:src="@{/resources/images/spring-logo.svg}"
alt="VMware Tanzu Logo"
class="logo"
>
</div>
</div>
</div>

View file

@ -4,7 +4,7 @@
<th:block th:fragment="select (label, name, items)">
<div th:with="valid=${!#fields.hasErrors(name)}"
th:class="${'form-group' + (valid ? '' : ' has-error')}"
class="form-group">
class="form-group mb-3">
<label class="col-sm-2 control-label" th:text="${label}">Label</label>
<div class="col-sm-10">

View file

@ -20,7 +20,7 @@
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button
th:with="text=${owner['new']} ? 'Add Owner' : 'Update Owner'"
th:with="text=${owner['newEntry']} ? 'Add Owner' : 'Update Owner'"
class="btn btn-primary" type="submit" th:text="${text}">Add
Owner</button>
</div>

View file

@ -12,8 +12,8 @@
<label class="col-sm-2 control-label">Last name </label>
<div class="col-sm-10">
<input class="form-control" th:field="*{lastName}" size="30"
maxlength="80" /> <span class="help-inline"><div
th:if="${#fields.hasAnyErrors()}">
maxlength="80" /> <span class="help-inline">
<div th:if="${#fields.hasAnyErrors()}">
<p th:each="err : ${#fields.allErrors()}" th:text="${err}">Error</p>
</div></span>
</div>

View file

@ -4,13 +4,13 @@
<body>
<h2>
<th:block th:if="${pet['new']}">New </th:block>
<th:block th:if="${pet['newEntry']}">New </th:block>
Pet
</h2>
<form th:object="${pet}" class="form-horizontal" method="post">
<input type="hidden" name="id" th:value="*{id}" />
<div class="form-group has-feedback">
<div class="form-group">
<div class="form-group mb-3">
<label class="col-sm-2 control-label">Owner</label>
<div class="col-sm-10">
<span th:text="${owner?.firstName + ' ' + owner?.lastName}" />
@ -26,11 +26,12 @@
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button
th:with="text=${pet['new']} ? 'Add Pet' : 'Update Pet'"
th:with="text=${pet['newEntry']} ? 'Add Pet' : 'Update Pet'"
class="btn btn-primary" type="submit" th:text="${text}">Add
Pet</button>
</div>
</div>
<div th:text="${error != null ? error: ''}"/>
</form>
</body>

View file

@ -4,7 +4,7 @@
<body>
<h2>
<th:block th:if="${visit['new']}">New </th:block>
<th:block th:if="${visit['newEntry']}">New </th:block>
Visit
</h2>
@ -51,7 +51,7 @@
<th>Date</th>
<th>Description</th>
</tr>
<tr th:if="${!visit['new']}" th:each="visit : ${pet.visits}">
<tr th:if="${!visit['newEntry']}" th:each="visit : ${pet.visits}">
<td th:text="${#temporals.format(visit.date, 'yyyy-MM-dd')}"></td>
<td th:text=" ${visit.description}"></td>
</tr>

View file

@ -1,16 +1,22 @@
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" th:replace="~{fragments/layout :: layout (~{::body},'home')}">
<html
xmlns:th="https://www.thymeleaf.org"
th:replace="~{fragments/layout :: layout (~{::body},'home')}"
>
<body>
<h2 th:text="#{welcome}">Welcome</h2>
<div class="row">
<div class="col-md-12">
<img class="img-responsive" src="../static/resources/images/pets.png" th:src="@{/resources/images/pets.png}"/>
<img
class="img-responsive"
src="../static/resources/images/pets.png"
th:src="@{/resources/images/pets.png}"
/>
</div>
</div>
</body>
</html>
</html>

View file

@ -47,6 +47,14 @@ $pagination-active-bg: $spring-brown;
$pagination-active-border: $spring-green;
$table-border-color: $spring-brown;
$asterisk: "\f069";
.asterisk{
&:after {
content: "*";
}
}
.table > thead > tr > th {
background-color: lighten($spring-brown, 3%);
color: $spring-light-grey;
@ -75,10 +83,10 @@ $table-border-color: $spring-brown;
&:hover,
&:focus,
&:active,
&.active,
.open .dropdown-toggle {
background-color: $spring-brown;
background-color: transparent;
color: $spring-green;
border-color: $spring-brown;
}
}

View file

@ -64,7 +64,9 @@ class MySqlIntegrationTests {
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
var request = RequestEntity.get("/owners/1").build();
ResponseEntity<String> result = template.exchange(request, String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}

View file

@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
@ -25,6 +25,10 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.samples.petclinic.Validation.InputValidator;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.OwnerRepository;
import org.springframework.samples.petclinic.owner.OwnerService;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.BDDMockito.given;
@ -54,6 +58,12 @@ class PetControllerTests {
@MockBean
private OwnerRepository owners;
@MockBean
private InputValidator inputValidator;
@MockBean
private OwnerService ownerService;
@BeforeEach
void setup() {
PetType cat = new PetType();
@ -64,7 +74,8 @@ class PetControllerTests {
Pet pet = new Pet();
owner.addPet(pet);
pet.setId(TEST_PET_ID);
given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
given(ownerService.findOwner(TEST_OWNER_ID)).willReturn(owner);
}
@Test

View file

@ -14,14 +14,12 @@
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
package org.springframework.samples.petclinic.Pet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
@ -32,6 +30,8 @@ import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.samples.petclinic.TestUtils.PetTypeTestUtil;
import org.springframework.samples.petclinic.owner.OwnerRepository;
/**
* Test class for {@link PetTypeFormatter}
@ -54,44 +54,31 @@ class PetTypeFormatterTests {
@Test
void testPrint() {
PetType petType = new PetType();
petType.setName("Hamster");
var hamster = PetTypes.HAMSTER.getValue();
var petType = PetTypeTestUtil.createPetType(hamster);
String petTypeName = this.petTypeFormatter.print(petType, Locale.ENGLISH);
assertThat(petTypeName).isEqualTo("Hamster");
assertThat(petTypeName).isEqualTo(hamster);
}
@Test
void shouldParse() throws ParseException {
given(this.pets.findPetTypes()).willReturn(makePetTypes());
PetType petType = petTypeFormatter.parse("Bird", Locale.ENGLISH);
assertThat(petType.getName()).isEqualTo("Bird");
mockFindPetTypes();
var bird = PetTypes.BIRD.getValue();
PetType petType = petTypeFormatter.parse(bird, Locale.ENGLISH);
assertThat(petType.getName()).isEqualTo(bird);
}
@Test
void shouldThrowParseException() throws ParseException {
given(this.pets.findPetTypes()).willReturn(makePetTypes());
mockFindPetTypes();
Assertions.assertThrows(ParseException.class, () -> {
petTypeFormatter.parse("Fish", Locale.ENGLISH);
});
}
/**
* Helper method to produce some sample pet types just for test purpose
* @return {@link Collection} of {@link PetType}
*/
private List<PetType> makePetTypes() {
List<PetType> petTypes = new ArrayList<>();
petTypes.add(new PetType() {
{
setName("Dog");
}
});
petTypes.add(new PetType() {
{
setName("Bird");
}
});
return petTypes;
private void mockFindPetTypes() {
List<PetType> petTypes = PetTypeTestUtil.createPetTypes(PetTypes.BIRD, PetTypes.DOG);
given(this.pets.findPetTypes()).willReturn(petTypes);
}
}

View file

@ -52,7 +52,9 @@ public class PetClinicIntegrationTests {
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
var request = RequestEntity.get("/owners/1").build();
ResponseEntity<String> result = template.exchange(request, String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}

View file

@ -47,8 +47,8 @@ import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.DockerClientFactory;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.docker.compose.skip.in-tests=false", //
"spring.docker.compose.profiles.active=postgres" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "spring.docker.compose.skip.in-tests=false", "spring.docker.compose.profiles.active=postgres" })
@ActiveProfiles("postgres")
@DisabledInNativeImage
public class PostgresIntegrationTests {
@ -68,12 +68,9 @@ public class PostgresIntegrationTests {
}
public static void main(String[] args) {
new SpringApplicationBuilder(PetClinicApplication.class) //
.profiles("postgres") //
.properties( //
"spring.docker.compose.profiles.active=postgres" //
) //
.listeners(new PropertiesLogger()) //
new SpringApplicationBuilder(PetClinicApplication.class).profiles("postgres")
.properties("spring.docker.compose.profiles.active=postgres")
.listeners(new PropertiesLogger())
.run(args);
}
@ -86,7 +83,9 @@ public class PostgresIntegrationTests {
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
var request = RequestEntity.get("/owners/1").build();
ResponseEntity<String> result = template.exchange(request, String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}

View file

@ -0,0 +1,41 @@
package org.springframework.samples.petclinic.TestUtils;
import lombok.NoArgsConstructor;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.owner.Owner;
import static org.springframework.samples.petclinic.TestUtils.PetTestUtil.createPet;
@NoArgsConstructor
public class OwnerTestUtil {
public static Owner createOwner() {
return createOwner(createPet());
}
public static Owner createOwner(Pet pet) {
var owner = new Owner();
owner.setId(1);
owner.setFirstName("firstName");
owner.setLastName("lastname");
owner.setAddress("110 W. Liberty St.");
owner.setCity("Madison");
owner.setTelephone("6085551023");
owner.addPet(pet);
return owner;
}
// TODO create custom Builder with Lombok (should also include Id from BaseEntity)
public static Owner createOwner(Integer ownerId, String firstName, String lastname, Pet pet) {
var owner = new Owner();
owner.setId(ownerId);
owner.setFirstName(firstName);
owner.setLastName(lastname);
owner.setAddress("110 W. Liberty St.");
owner.setCity("Madison");
owner.setTelephone("6085551023");
owner.addPet(pet);
return owner;
}
}

View file

@ -0,0 +1,44 @@
package org.springframework.samples.petclinic.TestUtils;
import lombok.NoArgsConstructor;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.Pet.PetType;
import org.springframework.samples.petclinic.Pet.PetTypes;
import org.springframework.samples.petclinic.owner.Visit;
import java.time.LocalDate;
import static org.springframework.samples.petclinic.TestUtils.VisitTestUtil.createVisit;
@NoArgsConstructor
public class PetTestUtil {
public static Pet createPet() {
var petType = PetTypeTestUtil.createPetType(PetTypes.CAT.getValue());
return createPet("Max", petType, createVisit());
}
public static Pet createPet(int petId) {
var petType = PetTypeTestUtil.createPetType(PetTypes.CAT.getValue());
return createPet(petId, "Max", petType, createVisit());
}
public static Pet createPet(String name, PetType petType) {
return createPet(name, petType, createVisit());
}
public static Pet createPet(String name, PetType petType, Visit visit) {
return createPet(1, name, petType, visit);
}
public static Pet createPet(int petId, String name, PetType petType, Visit visit) {
var pet = new Pet();
pet.setId(petId);
pet.setType(petType);
pet.setName(name);
pet.setBirthDate(LocalDate.now());
pet.addVisit(visit);
return pet;
}
}

View file

@ -0,0 +1,31 @@
package org.springframework.samples.petclinic.TestUtils;
import org.springframework.samples.petclinic.Pet.PetType;
import org.springframework.samples.petclinic.Pet.PetTypes;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PetTypeTestUtil {
public static PetType createPetType(String petTypeName) {
return createPetType(1, petTypeName);
}
public static PetType createPetType(int id, String petTypeName) {
var petType = new PetType();
petType.setName(petTypeName);
petType.setId(id);
return petType;
}
public static List<PetType> createPetTypes(PetTypes... petTypes) {
return Stream.of(petTypes).map(PetTypes::getValue).map(petTypeName -> {
var newpetType = new PetType();
newpetType.setName(petTypeName);
return newpetType;
}).collect(Collectors.toList());
}
}

View file

@ -0,0 +1,40 @@
package org.springframework.samples.petclinic.TestUtils;
import lombok.NoArgsConstructor;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.vet.Specialty;
import org.springframework.samples.petclinic.vet.Vet;
import static org.springframework.samples.petclinic.TestUtils.PetTestUtil.createPet;
@NoArgsConstructor
public class VetTestUtil {
public static Vet createVet() {
var vet = new Vet();
vet.setFirstName("James");
vet.setLastName("Carter");
vet.setId(1);
return vet;
}
public static Vet createVetWithSpecialty() {
var vet = createVet();
vet.setId(vet.getId() + 1);
vet.addSpecialty(createSpecialty());
return vet;
}
public static Specialty createSpecialty() {
return createSpecialty("radiology");
}
public static Specialty createSpecialty(String name) {
var specialty = new Specialty();
specialty.setId(1);
specialty.setName(name);
return specialty;
}
}

View file

@ -0,0 +1,25 @@
package org.springframework.samples.petclinic.TestUtils;
import lombok.NoArgsConstructor;
import org.springframework.samples.petclinic.owner.Visit;
import org.springframework.samples.petclinic.vet.Specialty;
import org.springframework.samples.petclinic.vet.Vet;
import java.time.LocalDate;
@NoArgsConstructor
public class VisitTestUtil {
public static Visit createVisit() {
return createVisit(LocalDate.now());
}
public static Visit createVisit(LocalDate localDate) {
var visit = new Visit();
visit.setId(1);
visit.setDate(localDate);
visit.setDescription("Just a visit");
return visit;
}
}

View file

@ -24,13 +24,14 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.springframework.samples.petclinic.TestUtils.OwnerTestUtil.createOwner;
import static org.springframework.samples.petclinic.TestUtils.PetTestUtil.createPet;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.time.LocalDate;
import java.util.List;
import org.assertj.core.util.Lists;
@ -46,6 +47,10 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.Pet.PetType;
import org.springframework.samples.petclinic.Pet.PetTypes;
import org.springframework.samples.petclinic.TestUtils.PetTypeTestUtil;
import org.springframework.test.web.servlet.MockMvc;
/**
@ -57,47 +62,36 @@ import org.springframework.test.web.servlet.MockMvc;
@DisabledInNativeImage
class OwnerControllerTests {
private static final int TEST_OWNER_ID = 1;
@Autowired
private MockMvc mockMvc;
@MockBean
private OwnerRepository owners;
@MockBean
private OwnerService ownerService;
private record TestData(int ownerId, String ownerFirstname, String ownerLastname, String petName, PetType petType) {
}
private final TestData testData = new TestData(1, "George", "Franklin", "Max",
PetTypeTestUtil.createPetType(PetTypes.DOG.getValue()));
private Owner george() {
Owner george = new Owner();
george.setId(TEST_OWNER_ID);
george.setFirstName("George");
george.setLastName("Franklin");
george.setAddress("110 W. Liberty St.");
george.setCity("Madison");
george.setTelephone("6085551023");
Pet max = new Pet();
PetType dog = new PetType();
dog.setName("dog");
max.setType(dog);
max.setName("Max");
max.setBirthDate(LocalDate.now());
george.addPet(max);
max.setId(1);
return george;
var pet = createPet(testData.petName, testData.petType);
var owner = createOwner(testData.ownerId, testData.ownerFirstname, testData.ownerLastname, pet);
return owner;
};
@BeforeEach
void setup() {
Owner george = george();
given(this.owners.findByLastName(eq("Franklin"), any(Pageable.class)))
given(this.owners.findByLastName(eq(testData.ownerLastname), any(Pageable.class)))
.willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
given(this.owners.findById(TEST_OWNER_ID)).willReturn(george);
Visit visit = new Visit();
visit.setDate(LocalDate.now());
george.getPet("Max").getVisits().add(visit);
given(ownerService.findOwner(testData.ownerId)).willReturn(george);
}
@Test
@ -148,10 +142,10 @@ class OwnerControllerTests {
@Test
void testProcessFindFormByLastName() throws Exception {
Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList(george()));
Mockito.when(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin"))
Mockito.when(this.owners.findByLastName(eq(testData.ownerLastname), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", testData.ownerLastname))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID));
.andExpect(view().name("redirect:/owners/" + testData.ownerId));
}
@Test
@ -168,11 +162,11 @@ class OwnerControllerTests {
@Test
void testInitUpdateOwnerForm() throws Exception {
mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID))
mockMvc.perform(get("/owners/{ownerId}/edit", testData.ownerId))
.andExpect(status().isOk())
.andExpect(model().attributeExists("owner"))
.andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin"))))
.andExpect(model().attribute("owner", hasProperty("firstName", is("George"))))
.andExpect(model().attribute("owner", hasProperty("lastName", is(testData.ownerLastname))))
.andExpect(model().attribute("owner", hasProperty("firstName", is(testData.ownerFirstname))))
.andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St."))))
.andExpect(model().attribute("owner", hasProperty("city", is("Madison"))))
.andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023"))))
@ -182,7 +176,7 @@ class OwnerControllerTests {
@Test
void testProcessUpdateOwnerFormSuccess() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe")
.perform(post("/owners/{ownerId}/edit", testData.ownerId).param("firstName", "Joe")
.param("lastName", "Bloggs")
.param("address", "123 Caramel Street")
.param("city", "London")
@ -193,7 +187,7 @@ class OwnerControllerTests {
@Test
void testProcessUpdateOwnerFormUnchangedSuccess() throws Exception {
mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID))
mockMvc.perform(post("/owners/{ownerId}/edit", testData.ownerId))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
}
@ -201,7 +195,7 @@ class OwnerControllerTests {
@Test
void testProcessUpdateOwnerFormHasErrors() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe")
.perform(post("/owners/{ownerId}/edit", testData.ownerId).param("firstName", "Joe")
.param("lastName", "Bloggs")
.param("address", "")
.param("telephone", ""))
@ -214,10 +208,10 @@ class OwnerControllerTests {
@Test
void testShowOwner() throws Exception {
mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID))
mockMvc.perform(get("/owners/{ownerId}", testData.ownerId))
.andExpect(status().isOk())
.andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin"))))
.andExpect(model().attribute("owner", hasProperty("firstName", is("George"))))
.andExpect(model().attribute("owner", hasProperty("lastName", is(testData.ownerLastname))))
.andExpect(model().attribute("owner", hasProperty("firstName", is(testData.ownerFirstname))))
.andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St."))))
.andExpect(model().attribute("owner", hasProperty("city", is("Madison"))))
.andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023"))))
@ -237,7 +231,7 @@ class OwnerControllerTests {
@Override
public void describeTo(Description description) {
description.appendText("Max did not have any visits");
description.appendText(testData.petName + " did not have any visits");
}
})))
.andExpect(view().name("owners/ownerDetails"));

View file

@ -17,6 +17,8 @@
package org.springframework.samples.petclinic.owner;
import static org.mockito.BDDMockito.given;
import static org.springframework.samples.petclinic.TestUtils.OwnerTestUtil.createOwner;
import static org.springframework.samples.petclinic.TestUtils.PetTestUtil.createPet;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
@ -29,8 +31,13 @@ import org.junit.jupiter.api.condition.DisabledInNativeImage;
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.boot.test.mock.mockito.SpyBean;
import org.springframework.samples.petclinic.Validation.InputValidator;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* Test class for {@link VisitController}
*
@ -50,12 +57,12 @@ class VisitControllerTests {
@MockBean
private OwnerRepository owners;
@SpyBean
private InputValidator inputValidator;
@BeforeEach
void init() {
Owner owner = new Owner();
Pet pet = new Pet();
owner.addPet(pet);
pet.setId(TEST_PET_ID);
var owner = createOwner(createPet(TEST_PET_ID));
given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
}
@ -86,4 +93,42 @@ class VisitControllerTests {
.andExpect(view().name("pets/createOrUpdateVisitForm"));
}
@Test
void testProcessUpdateFormHasError_For_EmptyDescription() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)
.param("description", "")
.param("date", "2015-02-12"))
.andExpect(model().attributeHasErrors("visit"))
.andExpect(model().attributeHasFieldErrorCode("visit", "description", "required"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdateVisitForm"));
}
@Test
void testProcessUpdateFormHasErrors_For_FutureDate() throws Exception {
var dateInFuture = LocalDate.now().plusYears(1);
mockMvc
.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)
.param("description", "hi")
.param("date", String.valueOf(dateInFuture)))
.andExpect(model().attributeHasErrors("visit"))
.andExpect(model().attributeHasFieldErrorCode("visit", "date", "typeMismatch.birthDate.future"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdateVisitForm"));
}
@Test
void testProcessUpdateFormHasErrors_For_EmptyDate() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)
.param("description", "hi")
.param("date", (String) null))
.andExpect(model().attributeHasErrors("visit"))
.andExpect(model().attributeHasFieldErrorCode("visit", "date", "typeMismatch.birthDate"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdateVisitForm"));
}
}

View file

@ -29,10 +29,11 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.samples.petclinic.Pet.Pet;
import org.springframework.samples.petclinic.Pet.PetType;
import org.springframework.samples.petclinic.Pet.PetTypes;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.OwnerRepository;
import org.springframework.samples.petclinic.owner.Pet;
import org.springframework.samples.petclinic.owner.PetType;
import org.springframework.samples.petclinic.owner.Visit;
import org.springframework.samples.petclinic.vet.Vet;
import org.springframework.samples.petclinic.vet.VetRepository;
@ -96,7 +97,7 @@ class ClinicServiceTests {
assertThat(owner.getLastName()).startsWith("Franklin");
assertThat(owner.getPets()).hasSize(1);
assertThat(owner.getPets().get(0).getType()).isNotNull();
assertThat(owner.getPets().get(0).getType().getName()).isEqualTo("cat");
assertThat(owner.getPets().get(0).getType().getName()).isEqualTo(PetTypes.CAT.getValue());
}
@Test
@ -111,6 +112,7 @@ class ClinicServiceTests {
owner.setAddress("4, Evans Street");
owner.setCity("Wollongong");
owner.setTelephone("4444444444");
this.owners.save(owner);
assertThat(owner.getId().longValue()).isNotEqualTo(0);
@ -138,9 +140,9 @@ class ClinicServiceTests {
Collection<PetType> petTypes = this.owners.findPetTypes();
PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1);
assertThat(petType1.getName()).isEqualTo("cat");
assertThat(petType1.getName()).isEqualTo(PetTypes.CAT.getValue());
PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4);
assertThat(petType4.getName()).isEqualTo("snake");
assertThat(petType4.getName()).isEqualTo(PetTypes.SNAKE.getValue());
}
@Test
@ -201,6 +203,7 @@ class ClinicServiceTests {
int found = pet7.getVisits().size();
Visit visit = new Visit();
visit.setDescription("test");
;
owner6.addVisit(pet7.getId(), visit);
this.owners.save(owner6);

View file

@ -51,10 +51,13 @@ class CrashControllerIntegrationTests {
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
static class TestConfiguration {
}
private static String BASE_URL = "http://localhost:";
@Value(value = "${local.server.port}")
private int port;
@ -63,8 +66,7 @@ class CrashControllerIntegrationTests {
@Test
void testTriggerExceptionJson() {
ResponseEntity<Map<String, Object>> resp = rest.exchange(
RequestEntity.get("http://localhost:" + port + "/oups").build(),
ResponseEntity<Map<String, Object>> resp = rest.exchange(RequestEntity.get(BASE_URL + port + "/oups").build(),
new ParameterizedTypeReference<Map<String, Object>>() {
});
assertThat(resp).isNotNull();
@ -81,7 +83,7 @@ class CrashControllerIntegrationTests {
void testTriggerExceptionHtml() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(List.of(MediaType.TEXT_HTML));
ResponseEntity<String> resp = rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET,
ResponseEntity<String> resp = rest.exchange(BASE_URL + port + "/oups", HttpMethod.GET,
new HttpEntity<>(headers), String.class);
assertThat(resp).isNotNull();
assertThat(resp.getStatusCode().is5xxServerError());

View file

@ -16,6 +16,7 @@
package org.springframework.samples.petclinic.system;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -31,16 +32,12 @@ import org.junit.jupiter.api.Test;
// luck ((plain(st) UNIT test)! :)
class CrashControllerTests {
CrashController testee = new CrashController();
CrashController crashController = new CrashController();
@Test
void testTriggerException() throws Exception {
RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
testee.triggerException();
});
assertEquals("Expected: controller used to showcase what happens when an exception is thrown",
thrown.getMessage());
assertThatThrownBy(() -> crashController.triggerException()).isInstanceOf(RuntimeException.class)
.hasMessage("Expected: controller used to showcase what happens when an exception is thrown");
}
}

View file

@ -32,6 +32,8 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.samples.petclinic.TestUtils.VetTestUtil.createVet;
import static org.springframework.samples.petclinic.TestUtils.VetTestUtil.createVetWithSpecialty;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ -49,31 +51,13 @@ class VetControllerTests {
@MockBean
private VetRepository vets;
private Vet james() {
Vet james = new Vet();
james.setFirstName("James");
james.setLastName("Carter");
james.setId(1);
return james;
}
private Vet helen() {
Vet helen = new Vet();
helen.setFirstName("Helen");
helen.setLastName("Leary");
helen.setId(2);
Specialty radiology = new Specialty();
radiology.setId(1);
radiology.setName("radiology");
helen.addSpecialty(radiology);
return helen;
}
@BeforeEach
void setup() {
given(this.vets.findAll()).willReturn(Lists.newArrayList(james(), helen()));
var vet = createVet();
var vetWithSpecialty = createVetWithSpecialty();
given(this.vets.findAll()).willReturn(Lists.newArrayList(vet, vetWithSpecialty));
given(this.vets.findAll(any(Pageable.class)))
.willReturn(new PageImpl<Vet>(Lists.newArrayList(james(), helen())));
.willReturn(new PageImpl<Vet>(Lists.newArrayList(vet, vetWithSpecialty)));
}

View file

@ -19,6 +19,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.util.SerializationUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.samples.petclinic.TestUtils.VetTestUtil.createVet;
/**
* @author Dave Syer
@ -27,15 +28,11 @@ class VetTests {
@Test
void testSerialization() {
Vet vet = new Vet();
vet.setFirstName("Zaphod");
vet.setLastName("Beeblebrox");
vet.setId(123);
var vet = createVet();
@SuppressWarnings("deprecation")
Vet other = (Vet) SerializationUtils.deserialize(SerializationUtils.serialize(vet));
assertThat(other.getFirstName()).isEqualTo(vet.getFirstName());
assertThat(other.getLastName()).isEqualTo(vet.getLastName());
assertThat(other.getId()).isEqualTo(vet.getId());
var other = (Vet) SerializationUtils.deserialize(SerializationUtils.serialize(vet));
assertThat(other.equals(vet));
}
}