diff --git a/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java b/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java index 191253587..bc0235fc7 100644 --- a/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java +++ b/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java @@ -1,35 +1,35 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * PetClinic Spring Boot Application. - * - * @author Dave Syer - * - */ -@SpringBootApplication(proxyBeanMethods = false) -public class PetClinicApplication { - - public static void main(String[] args) { - SpringApplication.run(PetClinicApplication.class, args); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * PetClinic Spring Boot Application. + * + * @author Dave Syer + * + */ +@SpringBootApplication(proxyBeanMethods = false) +public class PetClinicApplication { + + public static void main(String[] args) { + SpringApplication.run(PetClinicApplication.class, args); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java b/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java index 4cb9ffc0c..377a905a0 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java +++ b/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java @@ -1,51 +1,51 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.model; - -import java.io.Serializable; - -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; - -/** - * Simple JavaBean domain object with an id property. Used as a base class for objects - * needing this property. - * - * @author Ken Krebs - * @author Juergen Hoeller - */ -@MappedSuperclass -public class BaseEntity implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Integer id; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public boolean isNew() { - return this.id == null; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.model; + +import java.io.Serializable; + +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +/** + * Simple JavaBean domain object with an id property. Used as a base class for objects + * needing this property. + * + * @author Ken Krebs + * @author Juergen Hoeller + */ +@MappedSuperclass +public class BaseEntity implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isNew() { + return this.id == null; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java b/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java index 088e52e81..a793c70e1 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java +++ b/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java @@ -1,47 +1,47 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.model; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; - -/** - * Simple JavaBean domain object adds a name property to BaseEntity. Used as - * a base class for objects needing these properties. - * - * @author Ken Krebs - * @author Juergen Hoeller - */ -@MappedSuperclass -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; - } - - @Override - public String toString() { - return this.getName(); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.model; + +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; + +/** + * Simple JavaBean domain object adds a name property to BaseEntity. Used as + * a base class for objects needing these properties. + * + * @author Ken Krebs + * @author Juergen Hoeller + */ +@MappedSuperclass +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; + } + + @Override + public String toString() { + return this.getName(); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/model/Person.java b/src/main/java/org/springframework/samples/petclinic/model/Person.java index 15fabacc3..3afbe0ff0 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Person.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Person.java @@ -1,54 +1,54 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.model; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; -import javax.validation.constraints.NotEmpty; - -/** - * Simple JavaBean domain object representing an person. - * - * @author Ken Krebs - */ -@MappedSuperclass -public class Person extends BaseEntity { - - @Column(name = "first_name") - @NotEmpty - private String firstName; - - @Column(name = "last_name") - @NotEmpty - private String lastName; - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return this.lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.model; + +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; +import javax.validation.constraints.NotEmpty; + +/** + * Simple JavaBean domain object representing an person. + * + * @author Ken Krebs + */ +@MappedSuperclass +public class Person extends BaseEntity { + + @Column(name = "first_name") + @NotEmpty + private String firstName; + + @Column(name = "last_name") + @NotEmpty + private String lastName; + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return this.lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/model/package-info.java b/src/main/java/org/springframework/samples/petclinic/model/package-info.java index 37d6295e8..cee92bcb1 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/package-info.java +++ b/src/main/java/org/springframework/samples/petclinic/model/package-info.java @@ -1,20 +1,20 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * The classes in this package represent utilities used by the domain. - */ -package org.springframework.samples.petclinic.model; +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The classes in this package represent utilities used by the domain. + */ +package org.springframework.samples.petclinic.model; diff --git a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java index 61083bc8d..64877b64d 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java @@ -1,150 +1,150 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.validation.constraints.Digits; -import javax.validation.constraints.NotEmpty; - -import org.springframework.beans.support.MutableSortDefinition; -import org.springframework.beans.support.PropertyComparator; -import org.springframework.core.style.ToStringCreator; -import org.springframework.samples.petclinic.model.Person; - -/** - * Simple JavaBean domain object representing an owner. - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - */ -@Entity -@Table(name = "owners") -public class Owner extends Person { - - @Column(name = "address") - @NotEmpty - private String address; - - @Column(name = "city") - @NotEmpty - private String city; - - @Column(name = "telephone") - @NotEmpty - @Digits(fraction = 0, integer = 10) - private String telephone; - - @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner") - private Set pets; - - 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; - } - - protected Set getPetsInternal() { - if (this.pets == null) { - this.pets = new HashSet<>(); - } - return this.pets; - } - - protected void setPetsInternal(Set pets) { - this.pets = pets; - } - - public List getPets() { - List sortedPets = new ArrayList<>(getPetsInternal()); - PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true)); - return Collections.unmodifiableList(sortedPets); - } - - public void addPet(Pet pet) { - if (pet.isNew()) { - getPetsInternal().add(pet); - } - pet.setOwner(this); - } - - /** - * Return the Pet with the given name, or null if none found for this Owner. - * @param name to test - * @return true if pet name is already in use - */ - public Pet getPet(String name) { - return getPet(name, false); - } - - /** - * Return the Pet with the given name, or null if none found for this Owner. - * @param name to test - * @return true if pet name is already in use - */ - public Pet getPet(String name, boolean ignoreNew) { - name = name.toLowerCase(); - for (Pet pet : getPetsInternal()) { - if (!ignoreNew || !pet.isNew()) { - String compName = pet.getName(); - compName = compName.toLowerCase(); - if (compName.equals(name)) { - 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(); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotEmpty; + +import org.springframework.beans.support.MutableSortDefinition; +import org.springframework.beans.support.PropertyComparator; +import org.springframework.core.style.ToStringCreator; +import org.springframework.samples.petclinic.model.Person; + +/** + * Simple JavaBean domain object representing an owner. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + */ +@Entity +@Table(name = "owners") +public class Owner extends Person { + + @Column(name = "address") + @NotEmpty + private String address; + + @Column(name = "city") + @NotEmpty + private String city; + + @Column(name = "telephone") + @NotEmpty + @Digits(fraction = 0, integer = 10) + private String telephone; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner") + private Set pets; + + 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; + } + + protected Set getPetsInternal() { + if (this.pets == null) { + this.pets = new HashSet<>(); + } + return this.pets; + } + + protected void setPetsInternal(Set pets) { + this.pets = pets; + } + + public List getPets() { + List sortedPets = new ArrayList<>(getPetsInternal()); + PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true)); + return Collections.unmodifiableList(sortedPets); + } + + public void addPet(Pet pet) { + if (pet.isNew()) { + getPetsInternal().add(pet); + } + pet.setOwner(this); + } + + /** + * Return the Pet with the given name, or null if none found for this Owner. + * @param name to test + * @return true if pet name is already in use + */ + public Pet getPet(String name) { + return getPet(name, false); + } + + /** + * Return the Pet with the given name, or null if none found for this Owner. + * @param name to test + * @return true if pet name is already in use + */ + public Pet getPet(String name, boolean ignoreNew) { + name = name.toLowerCase(); + for (Pet pet : getPetsInternal()) { + if (!ignoreNew || !pet.isNew()) { + String compName = pet.getName(); + compName = compName.toLowerCase(); + if (compName.equals(name)) { + 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(); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java b/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java index 3314bf72d..7b4061163 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java @@ -1,158 +1,158 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import org.springframework.samples.petclinic.visit.VisitRepository; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -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.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.servlet.ModelAndView; - -import javax.validation.Valid; -import java.util.Collection; -import java.util.Map; - -/** - * @author Juergen Hoeller - * @author Ken Krebs - * @author Arjen Poutsma - * @author Michael Isvy - */ -@Controller -class OwnerController { - - private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm"; - - private final OwnerRepository owners; - - private VisitRepository visits; - - public OwnerController(OwnerRepository clinicService, VisitRepository visits) { - this.owners = clinicService; - this.visits = visits; - } - - @InitBinder - public void setAllowedFields(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } - - @GetMapping("/owners/new") - public String initCreationForm(Map model) { - Owner owner = new Owner(); - model.put("owner", owner); - return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; - } - - @PostMapping("/owners/new") - public String processCreationForm(@Valid Owner owner, BindingResult result) { - if (result.hasErrors()) { - return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; - } - else { - // let's check if an owner with the same name does not exist.. - verifyNameUnique(owner.getFirstName(), owner.getLastName()); - this.owners.save(owner); - return "redirect:/owners/" + owner.getId(); - } - } - - private void verifyNameUnique(String firstName, String lastName) { - for (int id : this.owners.getAllIds()) { - Owner other = owners.findById(id); - boolean sameFirstName = other.getFirstName().equals(firstName); - boolean sameLastName = other.getLastName().equals(lastName); - if (sameFirstName && sameLastName) { - throw new IllegalArgumentException("A Owner with the same name already exists!"); - } - } - } - - @GetMapping("/owners/find") - public String initFindForm(Map model) { - model.put("owner", new Owner()); - return "owners/findOwners"; - } - - @GetMapping("/owners") - public String processFindForm(Owner owner, BindingResult result, Map model) { - - // allow parameterless GET request for /owners to return all records - if (owner.getLastName() == null) { - owner.setLastName(""); // empty string signifies broadest possible search - } - - // find owners by last name - Collection results = this.owners.findByLastName(owner.getLastName()); - if (results.isEmpty()) { - // no owners found - result.rejectValue("lastName", "notFound", "not found"); - return "owners/findOwners"; - } - else if (results.size() == 1) { - // 1 owner found - owner = results.iterator().next(); - return "redirect:/owners/" + owner.getId(); - } - else { - // multiple owners found - model.put("selections", results); - return "owners/ownersList"; - } - } - - @GetMapping("/owners/{ownerId}/edit") - public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { - Owner owner = this.owners.findById(ownerId); - model.addAttribute(owner); - return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; - } - - @PostMapping("/owners/{ownerId}/edit") - public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, - @PathVariable("ownerId") int ownerId) { - if (result.hasErrors()) { - return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; - } - else { - owner.setId(ownerId); - this.owners.save(owner); - return "redirect:/owners/{ownerId}"; - } - } - - /** - * Custom handler for displaying an owner. - * @param ownerId the ID of the owner to display - * @return a ModelMap with the model attributes for the view - */ - @GetMapping("/owners/{ownerId}") - public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { - ModelAndView mav = new ModelAndView("owners/ownerDetails"); - Owner owner = this.owners.findById(ownerId); - for (Pet pet : owner.getPets()) { - pet.setVisitsInternal(visits.findByPetId(pet.getId())); - } - mav.addObject(owner); - return mav; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import org.springframework.samples.petclinic.visit.VisitRepository; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +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.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.servlet.ModelAndView; + +import javax.validation.Valid; +import java.util.Collection; +import java.util.Map; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + * @author Michael Isvy + */ +@Controller +class OwnerController { + + private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm"; + + private final OwnerRepository owners; + + private VisitRepository visits; + + public OwnerController(OwnerRepository clinicService, VisitRepository visits) { + this.owners = clinicService; + this.visits = visits; + } + + @InitBinder + public void setAllowedFields(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } + + @GetMapping("/owners/new") + public String initCreationForm(Map model) { + Owner owner = new Owner(); + model.put("owner", owner); + return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; + } + + @PostMapping("/owners/new") + public String processCreationForm(@Valid Owner owner, BindingResult result) { + if (result.hasErrors()) { + return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; + } + else { + // let's check if an owner with the same name does not exist.. + verifyNameUnique(owner.getFirstName(), owner.getLastName()); + this.owners.save(owner); + return "redirect:/owners/" + owner.getId(); + } + } + + private void verifyNameUnique(String firstName, String lastName) { + for (int id : this.owners.getAllIds()) { + Owner other = owners.findById(id); + boolean sameFirstName = other.getFirstName().equals(firstName); + boolean sameLastName = other.getLastName().equals(lastName); + if (sameFirstName && sameLastName) { + throw new IllegalArgumentException("A Owner with the same name already exists!"); + } + } + } + + @GetMapping("/owners/find") + public String initFindForm(Map model) { + model.put("owner", new Owner()); + return "owners/findOwners"; + } + + @GetMapping("/owners") + public String processFindForm(Owner owner, BindingResult result, Map model) { + + // allow parameterless GET request for /owners to return all records + if (owner.getLastName() == null) { + owner.setLastName(""); // empty string signifies broadest possible search + } + + // find owners by last name + Collection results = this.owners.findByLastName(owner.getLastName()); + if (results.isEmpty()) { + // no owners found + result.rejectValue("lastName", "notFound", "not found"); + return "owners/findOwners"; + } + else if (results.size() == 1) { + // 1 owner found + owner = results.iterator().next(); + return "redirect:/owners/" + owner.getId(); + } + else { + // multiple owners found + model.put("selections", results); + return "owners/ownersList"; + } + } + + @GetMapping("/owners/{ownerId}/edit") + public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { + Owner owner = this.owners.findById(ownerId); + model.addAttribute(owner); + return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; + } + + @PostMapping("/owners/{ownerId}/edit") + public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, + @PathVariable("ownerId") int ownerId) { + if (result.hasErrors()) { + return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; + } + else { + owner.setId(ownerId); + this.owners.save(owner); + return "redirect:/owners/{ownerId}"; + } + } + + /** + * Custom handler for displaying an owner. + * @param ownerId the ID of the owner to display + * @return a ModelMap with the model attributes for the view + */ + @GetMapping("/owners/{ownerId}") + public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { + ModelAndView mav = new ModelAndView("owners/ownerDetails"); + Owner owner = this.owners.findById(ownerId); + for (Pet pet : owner.getPets()) { + pet.setVisitsInternal(visits.findByPetId(pet.getId())); + } + mav.addObject(owner); + return mav; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java b/src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java index 118e205f9..e022d8d65 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java @@ -1,68 +1,68 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.util.Collection; -import java.util.List; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.Repository; -import org.springframework.data.repository.query.Param; -import org.springframework.transaction.annotation.Transactional; - -/** - * Repository class for Owner domain objects All method names are compliant - * with Spring Data naming conventions so this interface can easily be extended for Spring - * Data. See: - * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - */ -public interface OwnerRepository extends Repository { - - /** - * Retrieve {@link Owner}s from the data store by last name, returning all owners - * whose last name starts with the given name. - * @param lastName Value to search for - * @return a Collection of matching {@link Owner}s (or an empty Collection if none - * found) - */ - @Query("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName%") - @Transactional(readOnly = true) - Collection findByLastName(@Param("lastName") String lastName); - - /** - * Retrieve an {@link Owner} from the data store by id. - * @param id the id to search for - * @return the {@link Owner} if found - */ - @Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id") - @Transactional(readOnly = true) - Owner findById(@Param("id") Integer id); - - @Query("select o.id from Owner o") - List getAllIds(); - - /** - * Save an {@link Owner} to the data store, either inserting or updating it. - * @param owner the {@link Owner} to save - */ - void save(Owner owner); - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.util.Collection; +import java.util.List; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +/** + * Repository class for Owner domain objects All method names are compliant + * with Spring Data naming conventions so this interface can easily be extended for Spring + * Data. See: + * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + */ +public interface OwnerRepository extends Repository { + + /** + * Retrieve {@link Owner}s from the data store by last name, returning all owners + * whose last name starts with the given name. + * @param lastName Value to search for + * @return a Collection of matching {@link Owner}s (or an empty Collection if none + * found) + */ + @Query("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName%") + @Transactional(readOnly = true) + Collection findByLastName(@Param("lastName") String lastName); + + /** + * Retrieve an {@link Owner} from the data store by id. + * @param id the id to search for + * @return the {@link Owner} if found + */ + @Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id") + @Transactional(readOnly = true) + Owner findById(@Param("id") Integer id); + + @Query("select o.id from Owner o") + List getAllIds(); + + /** + * Save an {@link Owner} to the data store, either inserting or updating it. + * @param owner the {@link Owner} to save + */ + void save(Owner owner); + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/Pet.java b/src/main/java/org/springframework/samples/petclinic/owner/Pet.java index 2b68005fd..9149c3f97 100755 --- a/src/main/java/org/springframework/samples/petclinic/owner/Pet.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/Pet.java @@ -1,112 +1,112 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; - -import org.springframework.beans.support.MutableSortDefinition; -import org.springframework.beans.support.PropertyComparator; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.samples.petclinic.model.NamedEntity; -import org.springframework.samples.petclinic.visit.Visit; - -/** - * Simple business object representing a pet. - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - */ -@Entity -@Table(name = "pets") -public class Pet extends NamedEntity { - - @Column(name = "birth_date") - @DateTimeFormat(pattern = "yyyy-MM-dd") - private LocalDate birthDate; - - @ManyToOne - @JoinColumn(name = "type_id") - private PetType type; - - @ManyToOne - @JoinColumn(name = "owner_id") - private Owner owner; - - @Transient - private Set 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 Owner getOwner() { - return this.owner; - } - - protected void setOwner(Owner owner) { - this.owner = owner; - } - - protected Set getVisitsInternal() { - if (this.visits == null) { - this.visits = new HashSet<>(); - } - return this.visits; - } - - protected void setVisitsInternal(Collection visits) { - this.visits = new LinkedHashSet<>(visits); - } - - public List getVisits() { - List sortedVisits = new ArrayList<>(getVisitsInternal()); - PropertyComparator.sort(sortedVisits, new MutableSortDefinition("date", false, false)); - return Collections.unmodifiableList(sortedVisits); - } - - public void addVisit(Visit visit) { - getVisitsInternal().add(visit); - visit.setPetId(this.getId()); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Transient; + +import org.springframework.beans.support.MutableSortDefinition; +import org.springframework.beans.support.PropertyComparator; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.samples.petclinic.model.NamedEntity; +import org.springframework.samples.petclinic.visit.Visit; + +/** + * Simple business object representing a pet. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + */ +@Entity +@Table(name = "pets") +public class Pet extends NamedEntity { + + @Column(name = "birth_date") + @DateTimeFormat(pattern = "yyyy-MM-dd") + private LocalDate birthDate; + + @ManyToOne + @JoinColumn(name = "type_id") + private PetType type; + + @ManyToOne + @JoinColumn(name = "owner_id") + private Owner owner; + + @Transient + private Set 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 Owner getOwner() { + return this.owner; + } + + protected void setOwner(Owner owner) { + this.owner = owner; + } + + protected Set getVisitsInternal() { + if (this.visits == null) { + this.visits = new HashSet<>(); + } + return this.visits; + } + + protected void setVisitsInternal(Collection visits) { + this.visits = new LinkedHashSet<>(visits); + } + + public List getVisits() { + List sortedVisits = new ArrayList<>(getVisitsInternal()); + PropertyComparator.sort(sortedVisits, new MutableSortDefinition("date", false, false)); + return Collections.unmodifiableList(sortedVisits); + } + + public void addVisit(Visit visit) { + getVisitsInternal().add(visit); + visit.setPetId(this.getId()); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java index c59aa688c..014c2677d 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java @@ -1,124 +1,137 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -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.*; - -import javax.validation.Valid; -import java.util.Collection; - -/** - * @author Juergen Hoeller - * @author Ken Krebs - * @author Arjen Poutsma - */ -@Controller -@RequestMapping("/owners/{ownerId}") -class PetController { - - private static final String VIEWS_PETS_CREATE_OR_UPDATE_FORM = "pets/createOrUpdatePetForm"; - - private final PetRepository pets; - - private final OwnerRepository owners; - - public PetController(PetRepository pets, OwnerRepository owners) { - this.pets = pets; - this.owners = owners; - } - - @ModelAttribute("types") - public Collection populatePetTypes() { - return this.pets.findPetTypes(); - } - - @ModelAttribute("owner") - public Owner findOwner(@PathVariable("ownerId") int ownerId) { - return this.owners.findById(ownerId); - } - - @InitBinder("owner") - public void initOwnerBinder(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } - - @InitBinder("pet") - public void initPetBinder(WebDataBinder dataBinder) { - dataBinder.setValidator(new PetValidator()); - } - - @GetMapping("/pets/new") - public String initCreationForm(Owner owner, ModelMap model) { - Pet pet = new Pet(); - owner.addPet(pet); - model.put("pet", pet); - return VIEWS_PETS_CREATE_OR_UPDATE_FORM; - } - - @PostMapping("/pets/new") - public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) { - if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null) { - result.rejectValue("name", "duplicate", "already exists"); - } - if (pet.getName().equalsIgnoreCase("bugsy")) { - weDontLikeBugsyAroundHere(); - } - owner.addPet(pet); - if (result.hasErrors()) { - model.put("pet", pet); - return VIEWS_PETS_CREATE_OR_UPDATE_FORM; - } - else { - this.pets.save(pet); - return "redirect:/owners/{ownerId}"; - } - } - - private void weDontLikeBugsyAroundHere() { - try { - Thread.sleep(5000); - } - catch (InterruptedException e) { - } - } - - @GetMapping("/pets/{petId}/edit") - public String initUpdateForm(@PathVariable("petId") int petId, ModelMap model) { - Pet pet = this.pets.findById(petId); - model.put("pet", pet); - return VIEWS_PETS_CREATE_OR_UPDATE_FORM; - } - - @PostMapping("/pets/{petId}/edit") - public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) { - if (result.hasErrors()) { - pet.setOwner(owner); - model.put("pet", pet); - return VIEWS_PETS_CREATE_OR_UPDATE_FORM; - } - else { - owner.addPet(pet); - this.pets.save(pet); - return "redirect:/owners/{ownerId}"; - } - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +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.*; + +import javax.validation.Valid; +import java.util.Collection; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + */ +@Controller +@RequestMapping("/owners/{ownerId}") +class PetController { + + private static final String VIEWS_PETS_CREATE_OR_UPDATE_FORM = "pets/createOrUpdatePetForm"; + + private final PetRepository pets; + + private final OwnerRepository owners; + + public PetController(PetRepository pets, OwnerRepository owners) { + this.pets = pets; + this.owners = owners; + } + + @ModelAttribute("types") + public Collection populatePetTypes() { + return this.pets.findPetTypes(); + } + + @ModelAttribute("owner") + public Owner findOwner(@PathVariable("ownerId") int ownerId) { + return this.owners.findById(ownerId); + } + + @InitBinder("owner") + public void initOwnerBinder(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } + + @InitBinder("pet") + public void initPetBinder(WebDataBinder dataBinder) { + dataBinder.setValidator(new PetValidator()); + } + + @GetMapping("/pets/new") + public String initCreationForm(Owner owner, ModelMap model) { + Pet pet = new Pet(); + owner.addPet(pet); + model.put("pet", pet); + return VIEWS_PETS_CREATE_OR_UPDATE_FORM; + } + + @PostMapping("/pets/new") + public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) { + if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null) { + result.rejectValue("name", "duplicate", "already exists"); + } + + validatePetName(pet.getName()); + + owner.addPet(pet); + if (result.hasErrors()) { + model.put("pet", pet); + return VIEWS_PETS_CREATE_OR_UPDATE_FORM; + } + else { + this.pets.save(pet); + return "redirect:/owners/{ownerId}"; + } + } + + private void validatePetName(String name) { + long sleepDuration; + + if (name.equalsIgnoreCase("bugsy")) { + sleepDuration = (long) (3000 + Math.random() * 2000); + } + else { + sleepDuration = (long) (5 + Math.random() * 5); + } + + sleepDurationOf(sleepDuration); + } + + private void sleepDurationOf(long sleepDuration) { + try { + Thread.sleep(sleepDuration); + } + catch (InterruptedException e) { + } + } + + @GetMapping("/pets/{petId}/edit") + public String initUpdateForm(@PathVariable("petId") int petId, ModelMap model) { + Pet pet = this.pets.findById(petId); + model.put("pet", pet); + return VIEWS_PETS_CREATE_OR_UPDATE_FORM; + } + + @PostMapping("/pets/{petId}/edit") + public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) { + if (result.hasErrors()) { + pet.setOwner(owner); + model.put("pet", pet); + return VIEWS_PETS_CREATE_OR_UPDATE_FORM; + } + else { + owner.addPet(pet); + this.pets.save(pet); + return "redirect:/owners/{ownerId}"; + } + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetRepository.java b/src/main/java/org/springframework/samples/petclinic/owner/PetRepository.java index 9d25b095b..cfd70cee6 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetRepository.java @@ -1,59 +1,59 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.util.List; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.Repository; -import org.springframework.transaction.annotation.Transactional; - -/** - * Repository class for Pet domain objects All method names are compliant - * with Spring Data naming conventions so this interface can easily be extended for Spring - * Data. See: - * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - */ -public interface PetRepository extends Repository { - - /** - * Retrieve all {@link PetType}s from the data store. - * @return a Collection of {@link PetType}s. - */ - @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") - @Transactional(readOnly = true) - List findPetTypes(); - - /** - * Retrieve a {@link Pet} from the data store by id. - * @param id the id to search for - * @return the {@link Pet} if found - */ - @Transactional(readOnly = true) - Pet findById(Integer id); - - /** - * Save a {@link Pet} to the data store, either inserting or updating it. - * @param pet the {@link Pet} to save - */ - void save(Pet pet); - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.util.List; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.transaction.annotation.Transactional; + +/** + * Repository class for Pet domain objects All method names are compliant + * with Spring Data naming conventions so this interface can easily be extended for Spring + * Data. See: + * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + */ +public interface PetRepository extends Repository { + + /** + * Retrieve all {@link PetType}s from the data store. + * @return a Collection of {@link PetType}s. + */ + @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") + @Transactional(readOnly = true) + List findPetTypes(); + + /** + * Retrieve a {@link Pet} from the data store by id. + * @param id the id to search for + * @return the {@link Pet} if found + */ + @Transactional(readOnly = true) + Pet findById(Integer id); + + /** + * Save a {@link Pet} to the data store, either inserting or updating it. + * @param pet the {@link Pet} to save + */ + void save(Pet pet); + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetType.java b/src/main/java/org/springframework/samples/petclinic/owner/PetType.java index 6f0aa58d3..23c5d59a9 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetType.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetType.java @@ -1,30 +1,30 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import javax.persistence.Entity; -import javax.persistence.Table; - -import org.springframework.samples.petclinic.model.NamedEntity; - -/** - * @author Juergen Hoeller Can be Cat, Dog, Hamster... - */ -@Entity -@Table(name = "types") -public class PetType extends NamedEntity { - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import javax.persistence.Entity; +import javax.persistence.Table; + +import org.springframework.samples.petclinic.model.NamedEntity; + +/** + * @author Juergen Hoeller Can be Cat, Dog, Hamster... + */ +@Entity +@Table(name = "types") +public class PetType extends NamedEntity { + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java b/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java index 4940bcb38..e25422614 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java @@ -1,62 +1,62 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.text.ParseException; -import java.util.Collection; -import java.util.Locale; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.Formatter; -import org.springframework.stereotype.Component; - -/** - * Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting - * from Spring 3.0, Formatters have come as an improvement in comparison to legacy - * PropertyEditors. See the following links for more details: - The Spring ref doc: - * https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#format - * - * @author Mark Fisher - * @author Juergen Hoeller - * @author Michael Isvy - */ -@Component -public class PetTypeFormatter implements Formatter { - - private final PetRepository pets; - - @Autowired - public PetTypeFormatter(PetRepository pets) { - this.pets = pets; - } - - @Override - public String print(PetType petType, Locale locale) { - return petType.getName(); - } - - @Override - public PetType parse(String text, Locale locale) throws ParseException { - Collection findPetTypes = this.pets.findPetTypes(); - for (PetType type : findPetTypes) { - if (type.getName().equals(text)) { - return type; - } - } - throw new ParseException("type not found: " + text, 0); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.text.ParseException; +import java.util.Collection; +import java.util.Locale; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.Formatter; +import org.springframework.stereotype.Component; + +/** + * Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting + * from Spring 3.0, Formatters have come as an improvement in comparison to legacy + * PropertyEditors. See the following links for more details: - The Spring ref doc: + * https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#format + * + * @author Mark Fisher + * @author Juergen Hoeller + * @author Michael Isvy + */ +@Component +public class PetTypeFormatter implements Formatter { + + private final PetRepository pets; + + @Autowired + public PetTypeFormatter(PetRepository pets) { + this.pets = pets; + } + + @Override + public String print(PetType petType, Locale locale) { + return petType.getName(); + } + + @Override + public PetType parse(String text, Locale locale) throws ParseException { + Collection findPetTypes = this.pets.findPetTypes(); + for (PetType type : findPetTypes) { + if (type.getName().equals(text)) { + return type; + } + } + throw new ParseException("type not found: " + text, 0); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetValidator.java b/src/main/java/org/springframework/samples/petclinic/owner/PetValidator.java index e1370b428..c4f445b34 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetValidator.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetValidator.java @@ -1,64 +1,64 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import org.springframework.util.StringUtils; -import org.springframework.validation.Errors; -import org.springframework.validation.Validator; - -/** - * Validator for Pet forms. - *

- * We're not using Bean Validation annotations here because it is easier to define such - * validation rule in Java. - *

- * - * @author Ken Krebs - * @author Juergen Hoeller - */ -public class PetValidator implements Validator { - - private static final String REQUIRED = "required"; - - @Override - public void validate(Object obj, Errors errors) { - Pet pet = (Pet) obj; - String name = pet.getName(); - // name validation - if (!StringUtils.hasLength(name)) { - errors.rejectValue("name", REQUIRED, REQUIRED); - } - - // type validation - if (pet.isNew() && pet.getType() == null) { - errors.rejectValue("type", REQUIRED, REQUIRED); - } - - // birth date validation - if (pet.getBirthDate() == null) { - errors.rejectValue("birthDate", REQUIRED, REQUIRED); - } - } - - /** - * This Validator validates *just* Pet instances - */ - @Override - public boolean supports(Class clazz) { - return Pet.class.isAssignableFrom(clazz); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import org.springframework.util.StringUtils; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; + +/** + * Validator for Pet forms. + *

+ * We're not using Bean Validation annotations here because it is easier to define such + * validation rule in Java. + *

+ * + * @author Ken Krebs + * @author Juergen Hoeller + */ +public class PetValidator implements Validator { + + private static final String REQUIRED = "required"; + + @Override + public void validate(Object obj, Errors errors) { + Pet pet = (Pet) obj; + String name = pet.getName(); + // name validation + if (!StringUtils.hasLength(name)) { + errors.rejectValue("name", REQUIRED, REQUIRED); + } + + // type validation + if (pet.isNew() && pet.getType() == null) { + errors.rejectValue("type", REQUIRED, REQUIRED); + } + + // birth date validation + if (pet.getBirthDate() == null) { + errors.rejectValue("birthDate", REQUIRED, REQUIRED); + } + } + + /** + * This Validator validates *just* Pet instances + */ + @Override + public boolean supports(Class clazz) { + return Pet.class.isAssignableFrom(clazz); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/VisitController.java b/src/main/java/org/springframework/samples/petclinic/owner/VisitController.java index 375980312..7da35c745 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/VisitController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/VisitController.java @@ -1,92 +1,92 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.owner; - -import java.util.Map; - -import javax.validation.Valid; - -import org.springframework.samples.petclinic.visit.Visit; -import org.springframework.samples.petclinic.visit.VisitRepository; -import org.springframework.stereotype.Controller; -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; - -/** - * @author Juergen Hoeller - * @author Ken Krebs - * @author Arjen Poutsma - * @author Michael Isvy - * @author Dave Syer - */ -@Controller -class VisitController { - - private final VisitRepository visits; - - private final PetRepository pets; - - public VisitController(VisitRepository visits, PetRepository pets) { - this.visits = visits; - this.pets = pets; - } - - @InitBinder - public void setAllowedFields(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } - - /** - * Called before each and every @RequestMapping annotated method. 2 goals: - Make sure - * we always have fresh data - Since we do not use the session scope, make sure that - * Pet object always has an id (Even though id is not part of the form fields) - * @param petId - * @return Pet - */ - @ModelAttribute("visit") - public Visit loadPetWithVisit(@PathVariable("petId") int petId, Map model) { - Pet pet = this.pets.findById(petId); - pet.setVisitsInternal(this.visits.findByPetId(petId)); - model.put("pet", pet); - Visit visit = new Visit(); - pet.addVisit(visit); - return visit; - } - - // Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is called - @GetMapping("/owners/*/pets/{petId}/visits/new") - public String initNewVisitForm(@PathVariable("petId") int petId, Map model) { - return "pets/createOrUpdateVisitForm"; - } - - // Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is called - @PostMapping("/owners/{ownerId}/pets/{petId}/visits/new") - public String processNewVisitForm(@Valid Visit visit, BindingResult result) { - if (result.hasErrors()) { - return "pets/createOrUpdateVisitForm"; - } - else { - this.visits.save(visit); - return "redirect:/owners/{ownerId}"; - } - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.owner; + +import java.util.Map; + +import javax.validation.Valid; + +import org.springframework.samples.petclinic.visit.Visit; +import org.springframework.samples.petclinic.visit.VisitRepository; +import org.springframework.stereotype.Controller; +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; + +/** + * @author Juergen Hoeller + * @author Ken Krebs + * @author Arjen Poutsma + * @author Michael Isvy + * @author Dave Syer + */ +@Controller +class VisitController { + + private final VisitRepository visits; + + private final PetRepository pets; + + public VisitController(VisitRepository visits, PetRepository pets) { + this.visits = visits; + this.pets = pets; + } + + @InitBinder + public void setAllowedFields(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } + + /** + * Called before each and every @RequestMapping annotated method. 2 goals: - Make sure + * we always have fresh data - Since we do not use the session scope, make sure that + * Pet object always has an id (Even though id is not part of the form fields) + * @param petId + * @return Pet + */ + @ModelAttribute("visit") + public Visit loadPetWithVisit(@PathVariable("petId") int petId, Map model) { + Pet pet = this.pets.findById(petId); + pet.setVisitsInternal(this.visits.findByPetId(petId)); + model.put("pet", pet); + Visit visit = new Visit(); + pet.addVisit(visit); + return visit; + } + + // Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is called + @GetMapping("/owners/*/pets/{petId}/visits/new") + public String initNewVisitForm(@PathVariable("petId") int petId, Map model) { + return "pets/createOrUpdateVisitForm"; + } + + // Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is called + @PostMapping("/owners/{ownerId}/pets/{petId}/visits/new") + public String processNewVisitForm(@Valid Visit visit, BindingResult result) { + if (result.hasErrors()) { + return "pets/createOrUpdateVisitForm"; + } + else { + this.visits.save(visit); + return "redirect:/owners/{ownerId}"; + } + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java b/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java index 0a96582c9..98c628a50 100755 --- a/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java +++ b/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java @@ -1,55 +1,55 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.system; - -import javax.cache.configuration.MutableConfiguration; - -import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Cache configuration intended for caches providing the JCache API. This configuration - * creates the used cache for the application and enables statistics that become - * accessible via JMX. - */ -@Configuration(proxyBeanMethods = false) -@EnableCaching -class CacheConfiguration { - - @Bean - public JCacheManagerCustomizer petclinicCacheConfigurationCustomizer() { - return cm -> { - cm.createCache("vets", cacheConfiguration()); - }; - } - - /** - * Create a simple configuration that enable statistics via the JCache programmatic - * configuration API. - *

- * Within the configuration object that is provided by the JCache API standard, there - * is only a very limited set of configuration options. The really relevant - * configuration options (like the size limit) must be set via a configuration - * mechanism that is provided by the selected JCache implementation. - */ - private javax.cache.configuration.Configuration cacheConfiguration() { - return new MutableConfiguration<>().setStatisticsEnabled(true); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.system; + +import javax.cache.configuration.MutableConfiguration; + +import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Cache configuration intended for caches providing the JCache API. This configuration + * creates the used cache for the application and enables statistics that become + * accessible via JMX. + */ +@Configuration(proxyBeanMethods = false) +@EnableCaching +class CacheConfiguration { + + @Bean + public JCacheManagerCustomizer petclinicCacheConfigurationCustomizer() { + return cm -> { + cm.createCache("vets", cacheConfiguration()); + }; + } + + /** + * Create a simple configuration that enable statistics via the JCache programmatic + * configuration API. + *

+ * Within the configuration object that is provided by the JCache API standard, there + * is only a very limited set of configuration options. The really relevant + * configuration options (like the size limit) must be set via a configuration + * mechanism that is provided by the selected JCache implementation. + */ + private javax.cache.configuration.Configuration cacheConfiguration() { + return new MutableConfiguration<>().setStatisticsEnabled(true); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/system/CrashController.java b/src/main/java/org/springframework/samples/petclinic/system/CrashController.java index 2b28600fd..b8b6ce3c1 100644 --- a/src/main/java/org/springframework/samples/petclinic/system/CrashController.java +++ b/src/main/java/org/springframework/samples/petclinic/system/CrashController.java @@ -1,37 +1,37 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.system; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -/** - * Controller used to showcase what happens when an exception is thrown - * - * @author Michael Isvy - *

- * Also see how a view that resolves to "error" has been added ("error.html"). - */ -@Controller -class CrashController { - - @GetMapping("/oups") - public String triggerException() { - throw new RuntimeException( - "Expected: controller used to showcase what " + "happens when an exception is thrown"); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.system; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * Controller used to showcase what happens when an exception is thrown + * + * @author Michael Isvy + *

+ * Also see how a view that resolves to "error" has been added ("error.html"). + */ +@Controller +class CrashController { + + @GetMapping("/oups") + public String triggerException() { + throw new RuntimeException( + "Expected: controller used to showcase what " + "happens when an exception is thrown"); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/system/DataBasePopulator.java b/src/main/java/org/springframework/samples/petclinic/system/DataBasePopulator.java index e3673471a..afee26b4c 100644 --- a/src/main/java/org/springframework/samples/petclinic/system/DataBasePopulator.java +++ b/src/main/java/org/springframework/samples/petclinic/system/DataBasePopulator.java @@ -1,66 +1,66 @@ -package org.springframework.samples.petclinic.system; - -import com.devskiller.jfairy.Bootstrap; -import com.devskiller.jfairy.Fairy; -import com.devskiller.jfairy.producer.person.Person; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.samples.petclinic.owner.*; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.transaction.Transactional; -import java.util.List; -import java.util.Locale; -import java.util.Random; - -@Component -public class DataBasePopulator { - - private final int NUM_OWNERS_TO_ADD = 100; - - private final int PETS_PER_OWNER = 3; - - @Autowired - private OwnerRepository ownerRepo; - - @Autowired - private PetRepository petRepo; - - @PostConstruct - @Transactional - void addMoreOwnersAndPets() { - - Random numberGen = new Random(42); - - List petTypes = petRepo.findPetTypes(); - - Fairy ownerGen = Bootstrap.builder().withLocale(Locale.ENGLISH) // english owners - // ... - .withRandomSeed(42).build(); - Fairy petGen = Bootstrap.builder().withLocale(Locale.FRENCH) // with french pets - .withRandomSeed(42).build(); - - for (int i = 0; i < NUM_OWNERS_TO_ADD; i++) { - Person p = ownerGen.person(); - Owner newOwner = new Owner(); - newOwner.setAddress(p.getAddress().getAddressLine1()); - newOwner.setCity(p.getAddress().getCity()); - newOwner.setTelephone("1234567890"); - newOwner.setFirstName(p.getFirstName()); - newOwner.setLastName(p.getLastName()); - - double petCount = numberGen.nextDouble() * PETS_PER_OWNER; - for (int j = 0; j <= petCount; j++) { - Person pe = petGen.person(); - Pet pet = new Pet(); - pet.setBirthDate(pe.getDateOfBirth()); - pet.setName(pe.getFirstName()); - pet.setType(petTypes.get((int) (numberGen.nextDouble() * petTypes.size()))); - newOwner.addPet(pet); - } - - ownerRepo.save(newOwner); - } - } - -} +package org.springframework.samples.petclinic.system; + +import com.devskiller.jfairy.Bootstrap; +import com.devskiller.jfairy.Fairy; +import com.devskiller.jfairy.producer.person.Person; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.samples.petclinic.owner.*; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.transaction.Transactional; +import java.util.List; +import java.util.Locale; +import java.util.Random; + +@Component +public class DataBasePopulator { + + private final int NUM_OWNERS_TO_ADD = 100; + + private final int PETS_PER_OWNER = 3; + + @Autowired + private OwnerRepository ownerRepo; + + @Autowired + private PetRepository petRepo; + + @PostConstruct + @Transactional + void addMoreOwnersAndPets() { + + Random numberGen = new Random(42); + + List petTypes = petRepo.findPetTypes(); + + Fairy ownerGen = Bootstrap.builder().withLocale(Locale.ENGLISH) // english owners + // ... + .withRandomSeed(42).build(); + Fairy petGen = Bootstrap.builder().withLocale(Locale.FRENCH) // with french pets + .withRandomSeed(42).build(); + + for (int i = 0; i < NUM_OWNERS_TO_ADD; i++) { + Person p = ownerGen.person(); + Owner newOwner = new Owner(); + newOwner.setAddress(p.getAddress().getAddressLine1()); + newOwner.setCity(p.getAddress().getCity()); + newOwner.setTelephone("1234567890"); + newOwner.setFirstName(p.getFirstName()); + newOwner.setLastName(p.getLastName()); + + double petCount = numberGen.nextDouble() * PETS_PER_OWNER; + for (int j = 0; j <= petCount; j++) { + Person pe = petGen.person(); + Pet pet = new Pet(); + pet.setBirthDate(pe.getDateOfBirth()); + pet.setName(pe.getFirstName()); + pet.setType(petTypes.get((int) (numberGen.nextDouble() * petTypes.size()))); + newOwner.addPet(pet); + } + + ownerRepo.save(newOwner); + } + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/system/EumInterceptorConfiguration.java b/src/main/java/org/springframework/samples/petclinic/system/EumInterceptorConfiguration.java index 4cb4e3033..337352e82 100755 --- a/src/main/java/org/springframework/samples/petclinic/system/EumInterceptorConfiguration.java +++ b/src/main/java/org/springframework/samples/petclinic/system/EumInterceptorConfiguration.java @@ -1,37 +1,37 @@ -package org.springframework.samples.petclinic.system; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Configuration -public class EumInterceptorConfiguration implements WebMvcConfigurer { - - @Value("${eum.server:}") - String eumUrl; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new HandlerInterceptor() { - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) { - - if (!StringUtils.isEmpty(eumUrl) && modelAndView != null) { - String viewName = modelAndView.getViewName(); - if (viewName != null && !viewName.startsWith("redirect:")) { - modelAndView.addObject("eumserver", eumUrl); - } - } - } - }); - } - -} +package org.springframework.samples.petclinic.system; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Configuration +public class EumInterceptorConfiguration implements WebMvcConfigurer { + + @Value("${eum.server:}") + String eumUrl; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new HandlerInterceptor() { + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) { + + if (!StringUtils.isEmpty(eumUrl) && modelAndView != null) { + String viewName = modelAndView.getViewName(); + if (viewName != null && !viewName.startsWith("redirect:")) { + modelAndView.addObject("eumserver", eumUrl); + } + } + } + }); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java b/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java index 9224015bc..9dd083413 100644 --- a/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java +++ b/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java @@ -1,30 +1,30 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.system; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -class WelcomeController { - - @GetMapping("/") - public String welcome() { - return "welcome"; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.system; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +class WelcomeController { + + @GetMapping("/") + public String welcome() { + return "welcome"; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/vet/Specialty.java b/src/main/java/org/springframework/samples/petclinic/vet/Specialty.java index ea8ec6ded..f692c24cc 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/Specialty.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/Specialty.java @@ -1,34 +1,34 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Table; - -import org.springframework.samples.petclinic.model.NamedEntity; - -/** - * Models a {@link Vet Vet's} specialty (for example, dentistry). - * - * @author Juergen Hoeller - */ -@Entity -@Table(name = "specialties") -public class Specialty extends NamedEntity implements Serializable { - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Table; + +import org.springframework.samples.petclinic.model.NamedEntity; + +/** + * Models a {@link Vet Vet's} specialty (for example, dentistry). + * + * @author Juergen Hoeller + */ +@Entity +@Table(name = "specialties") +public class Specialty extends NamedEntity implements Serializable { + +} diff --git a/src/main/java/org/springframework/samples/petclinic/vet/Vet.java b/src/main/java/org/springframework/samples/petclinic/vet/Vet.java index 014becfce..e2b54c8d9 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/Vet.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/Vet.java @@ -1,79 +1,79 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlElement; - -import org.springframework.beans.support.MutableSortDefinition; -import org.springframework.beans.support.PropertyComparator; -import org.springframework.samples.petclinic.model.Person; - -/** - * Simple JavaBean domain object representing a veterinarian. - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Arjen Poutsma - */ -@Entity -@Table(name = "vets") -public class Vet extends Person { - - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"), - inverseJoinColumns = @JoinColumn(name = "specialty_id")) - private Set specialties; - - protected Set getSpecialtiesInternal() { - if (this.specialties == null) { - this.specialties = new HashSet<>(); - } - return this.specialties; - } - - protected void setSpecialtiesInternal(Set specialties) { - this.specialties = specialties; - } - - @XmlElement - public List getSpecialties() { - List sortedSpecs = new ArrayList<>(getSpecialtiesInternal()); - PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true)); - return Collections.unmodifiableList(sortedSpecs); - } - - public int getNrOfSpecialties() { - return getSpecialtiesInternal().size(); - } - - public void addSpecialty(Specialty specialty) { - getSpecialtiesInternal().add(specialty); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlElement; + +import org.springframework.beans.support.MutableSortDefinition; +import org.springframework.beans.support.PropertyComparator; +import org.springframework.samples.petclinic.model.Person; + +/** + * Simple JavaBean domain object representing a veterinarian. + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Arjen Poutsma + */ +@Entity +@Table(name = "vets") +public class Vet extends Person { + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"), + inverseJoinColumns = @JoinColumn(name = "specialty_id")) + private Set specialties; + + protected Set getSpecialtiesInternal() { + if (this.specialties == null) { + this.specialties = new HashSet<>(); + } + return this.specialties; + } + + protected void setSpecialtiesInternal(Set specialties) { + this.specialties = specialties; + } + + @XmlElement + public List getSpecialties() { + List sortedSpecs = new ArrayList<>(getSpecialtiesInternal()); + PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true)); + return Collections.unmodifiableList(sortedSpecs); + } + + public int getNrOfSpecialties() { + return getSpecialtiesInternal().size(); + } + + public void addSpecialty(Specialty specialty) { + getSpecialtiesInternal().add(specialty); + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/vet/VetController.java b/src/main/java/org/springframework/samples/petclinic/vet/VetController.java index fb5e321ba..183132f1f 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/VetController.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/VetController.java @@ -1,58 +1,58 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import java.util.Map; - -/** - * @author Juergen Hoeller - * @author Mark Fisher - * @author Ken Krebs - * @author Arjen Poutsma - */ -@Controller -class VetController { - - private final VetRepository vets; - - public VetController(VetRepository clinicService) { - this.vets = clinicService; - } - - @GetMapping("/vets.html") - public String showVetList(Map 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(); - vets.getVetList().addAll(this.vets.findAll()); - model.put("vets", vets); - return "vets/vetList"; - } - - @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.vets.findAll()); - return vets; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.Map; + +/** + * @author Juergen Hoeller + * @author Mark Fisher + * @author Ken Krebs + * @author Arjen Poutsma + */ +@Controller +class VetController { + + private final VetRepository vets; + + public VetController(VetRepository clinicService) { + this.vets = clinicService; + } + + @GetMapping("/vets.html") + public String showVetList(Map 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(); + vets.getVetList().addAll(this.vets.findAll()); + model.put("vets", vets); + return "vets/vetList"; + } + + @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.vets.findAll()); + return vets; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/vet/VetRepository.java b/src/main/java/org/springframework/samples/petclinic/vet/VetRepository.java index 549b1c229..20d1e5179 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/VetRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/VetRepository.java @@ -1,46 +1,46 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import java.util.Collection; - -import org.springframework.cache.annotation.Cacheable; -import org.springframework.dao.DataAccessException; -import org.springframework.data.repository.Repository; -import org.springframework.transaction.annotation.Transactional; - -/** - * Repository class for Vet domain objects All method names are compliant - * with Spring Data naming conventions so this interface can easily be extended for Spring - * Data. See: - * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - */ -public interface VetRepository extends Repository { - - /** - * Retrieve all Vets from the data store. - * @return a Collection of Vets - */ - @Transactional(readOnly = true) - @Cacheable("vets") - Collection findAll() throws DataAccessException; - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import java.util.Collection; + +import org.springframework.cache.annotation.Cacheable; +import org.springframework.dao.DataAccessException; +import org.springframework.data.repository.Repository; +import org.springframework.transaction.annotation.Transactional; + +/** + * Repository class for Vet domain objects All method names are compliant + * with Spring Data naming conventions so this interface can easily be extended for Spring + * Data. See: + * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + */ +public interface VetRepository extends Repository { + + /** + * Retrieve all Vets from the data store. + * @return a Collection of Vets + */ + @Transactional(readOnly = true) + @Cacheable("vets") + Collection findAll() throws DataAccessException; + +} diff --git a/src/main/java/org/springframework/samples/petclinic/vet/Vets.java b/src/main/java/org/springframework/samples/petclinic/vet/Vets.java index cea665629..8b1f300e5 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/Vets.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/Vets.java @@ -1,43 +1,43 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Simple domain object representing a list of veterinarians. Mostly here to be used for - * the 'vets' {@link org.springframework.web.servlet.view.xml.MarshallingView}. - * - * @author Arjen Poutsma - */ -@XmlRootElement -public class Vets { - - private List vets; - - @XmlElement - public List getVetList() { - if (vets == null) { - vets = new ArrayList<>(); - } - return vets; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Simple domain object representing a list of veterinarians. Mostly here to be used for + * the 'vets' {@link org.springframework.web.servlet.view.xml.MarshallingView}. + * + * @author Arjen Poutsma + */ +@XmlRootElement +public class Vets { + + private List vets; + + @XmlElement + public List getVetList() { + if (vets == null) { + vets = new ArrayList<>(); + } + return vets; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/visit/Visit.java b/src/main/java/org/springframework/samples/petclinic/visit/Visit.java index df9f25fe0..48d376a0b 100755 --- a/src/main/java/org/springframework/samples/petclinic/visit/Visit.java +++ b/src/main/java/org/springframework/samples/petclinic/visit/Visit.java @@ -1,80 +1,80 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.visit; - -import java.time.LocalDate; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.validation.constraints.NotEmpty; - -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.samples.petclinic.model.BaseEntity; - -/** - * Simple JavaBean domain object representing a visit. - * - * @author Ken Krebs - * @author Dave Syer - */ -@Entity -@Table(name = "visits") -public class Visit extends BaseEntity { - - @Column(name = "visit_date") - @DateTimeFormat(pattern = "yyyy-MM-dd") - private LocalDate date; - - @NotEmpty - @Column(name = "description") - private String description; - - @Column(name = "pet_id") - private Integer petId; - - /** - * 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; - } - - public Integer getPetId() { - return this.petId; - } - - public void setPetId(Integer petId) { - this.petId = petId; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.visit; + +import java.time.LocalDate; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.validation.constraints.NotEmpty; + +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.samples.petclinic.model.BaseEntity; + +/** + * Simple JavaBean domain object representing a visit. + * + * @author Ken Krebs + * @author Dave Syer + */ +@Entity +@Table(name = "visits") +public class Visit extends BaseEntity { + + @Column(name = "visit_date") + @DateTimeFormat(pattern = "yyyy-MM-dd") + private LocalDate date; + + @NotEmpty + @Column(name = "description") + private String description; + + @Column(name = "pet_id") + private Integer petId; + + /** + * 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; + } + + public Integer getPetId() { + return this.petId; + } + + public void setPetId(Integer petId) { + this.petId = petId; + } + +} diff --git a/src/main/java/org/springframework/samples/petclinic/visit/VisitRepository.java b/src/main/java/org/springframework/samples/petclinic/visit/VisitRepository.java index d5a3334c6..aa1dc6ea8 100644 --- a/src/main/java/org/springframework/samples/petclinic/visit/VisitRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/visit/VisitRepository.java @@ -1,46 +1,46 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.visit; - -import java.util.List; - -import org.springframework.dao.DataAccessException; -import org.springframework.data.repository.Repository; -import org.springframework.samples.petclinic.model.BaseEntity; - -/** - * Repository class for Visit domain objects All method names are compliant - * with Spring Data naming conventions so this interface can easily be extended for Spring - * Data. See: - * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - */ -public interface VisitRepository extends Repository { - - /** - * Save a Visit to the data store, either inserting or updating it. - * @param visit the Visit to save - * @see BaseEntity#isNew - */ - void save(Visit visit) throws DataAccessException; - - List findByPetId(Integer petId); - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.visit; + +import java.util.List; + +import org.springframework.dao.DataAccessException; +import org.springframework.data.repository.Repository; +import org.springframework.samples.petclinic.model.BaseEntity; + +/** + * Repository class for Visit domain objects All method names are compliant + * with Spring Data naming conventions so this interface can easily be extended for Spring + * Data. See: + * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation + * + * @author Ken Krebs + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + */ +public interface VisitRepository extends Repository { + + /** + * Save a Visit to the data store, either inserting or updating it. + * @param visit the Visit to save + * @see BaseEntity#isNew + */ + void save(Visit visit) throws DataAccessException; + + List findByPetId(Integer petId); + +} diff --git a/src/test/java/org/springframework/samples/petclinic/PetclinicIntegrationTests.java b/src/test/java/org/springframework/samples/petclinic/PetclinicIntegrationTests.java index 226db01fe..d42278759 100644 --- a/src/test/java/org/springframework/samples/petclinic/PetclinicIntegrationTests.java +++ b/src/test/java/org/springframework/samples/petclinic/PetclinicIntegrationTests.java @@ -1,36 +1,36 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.samples.petclinic.vet.VetRepository; - -@SpringBootTest -class PetclinicIntegrationTests { - - @Autowired - private VetRepository vets; - - @Test - void testFindAll() throws Exception { - vets.findAll(); - vets.findAll(); // served from cache - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.samples.petclinic.vet.VetRepository; + +@SpringBootTest +class PetclinicIntegrationTests { + + @Autowired + private VetRepository vets; + + @Test + void testFindAll() throws Exception { + vets.findAll(); + vets.findAll(); // served from cache + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java b/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java index 8d754900d..eb2a6b170 100644 --- a/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java +++ b/src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java @@ -1,60 +1,60 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.model; - -import java.util.Locale; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validator; - -import org.junit.jupiter.api.Test; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @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) - */ -class ValidatorTests { - - private Validator createValidator() { - LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); - localValidatorFactoryBean.afterPropertiesSet(); - return localValidatorFactoryBean; - } - - @Test - void shouldNotValidateWhenFirstNameEmpty() { - - LocaleContextHolder.setLocale(Locale.ENGLISH); - Person person = new Person(); - person.setFirstName(""); - person.setLastName("smith"); - - Validator validator = createValidator(); - Set> constraintViolations = validator.validate(person); - - assertThat(constraintViolations).hasSize(1); - ConstraintViolation violation = constraintViolations.iterator().next(); - assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); - assertThat(violation.getMessage()).isEqualTo("must not be empty"); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.model; + +import java.util.Locale; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validator; + +import org.junit.jupiter.api.Test; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @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) + */ +class ValidatorTests { + + private Validator createValidator() { + LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); + localValidatorFactoryBean.afterPropertiesSet(); + return localValidatorFactoryBean; + } + + @Test + void shouldNotValidateWhenFirstNameEmpty() { + + LocaleContextHolder.setLocale(Locale.ENGLISH); + Person person = new Person(); + person.setFirstName(""); + person.setLastName("smith"); + + Validator validator = createValidator(); + Set> constraintViolations = validator.validate(person); + + assertThat(constraintViolations).hasSize(1); + ConstraintViolation violation = constraintViolations.iterator().next(); + assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); + assertThat(violation.getMessage()).isEqualTo("must not be empty"); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java index 1d6249c5d..48f42be83 100644 --- a/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java @@ -1,199 +1,199 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.owner; - -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import org.assertj.core.util.Lists; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -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.samples.petclinic.visit.Visit; -import org.springframework.samples.petclinic.visit.VisitRepository; -import org.springframework.test.web.servlet.MockMvc; - -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.mockito.BDDMockito.given; -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; - -/** - * Test class for {@link OwnerController} - * - * @author Colin But - */ -@WebMvcTest(OwnerController.class) -class OwnerControllerTests { - - private static final int TEST_OWNER_ID = 1; - - @Autowired - private MockMvc mockMvc; - - @MockBean - private OwnerRepository owners; - - @MockBean - private VisitRepository visits; - - private Owner george; - - @BeforeEach - void setup() { - 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.setId(1); - max.setType(dog); - max.setName("Max"); - max.setBirthDate(LocalDate.now()); - george.setPetsInternal(Collections.singleton(max)); - given(this.owners.findById(TEST_OWNER_ID)).willReturn(george); - Visit visit = new Visit(); - visit.setDate(LocalDate.now()); - given(this.visits.findByPetId(max.getId())).willReturn(Collections.singletonList(visit)); - } - - @Test - void testInitCreationForm() throws Exception { - mockMvc.perform(get("/owners/new")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); - } - - @Test - void testProcessCreationFormSuccess() throws Exception { - mockMvc.perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs") - .param("address", "123 Caramel Street").param("city", "London").param("telephone", "01316761638")) - .andExpect(status().is3xxRedirection()); - } - - @Test - void testProcessCreationFormHasErrors() throws Exception { - mockMvc.perform( - post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London")) - .andExpect(status().isOk()).andExpect(model().attributeHasErrors("owner")) - .andExpect(model().attributeHasFieldErrors("owner", "address")) - .andExpect(model().attributeHasFieldErrors("owner", "telephone")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); - } - - @Test - void testInitFindForm() throws Exception { - mockMvc.perform(get("/owners/find")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) - .andExpect(view().name("owners/findOwners")); - } - - @Test - void testProcessFindFormSuccess() throws Exception { - given(this.owners.findByLastName("")).willReturn(Lists.newArrayList(george, new Owner())); - mockMvc.perform(get("/owners")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList")); - } - - @Test - void testProcessFindFormByLastName() throws Exception { - given(this.owners.findByLastName(george.getLastName())).willReturn(Lists.newArrayList(george)); - mockMvc.perform(get("/owners").param("lastName", "Franklin")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID)); - } - - @Test - void testProcessFindFormNoOwnersFound() throws Exception { - mockMvc.perform(get("/owners").param("lastName", "Unknown Surname")).andExpect(status().isOk()) - .andExpect(model().attributeHasFieldErrors("owner", "lastName")) - .andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound")) - .andExpect(view().name("owners/findOwners")); - } - - @Test - void testInitUpdateOwnerForm() throws Exception { - mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)).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("address", is("110 W. Liberty St.")))) - .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) - .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); - } - - @Test - void testProcessUpdateOwnerFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") - .param("lastName", "Bloggs").param("address", "123 Caramel Street").param("city", "London") - .param("telephone", "01616291589")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); - } - - @Test - void testProcessUpdateOwnerFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") - .param("lastName", "Bloggs").param("city", "London")).andExpect(status().isOk()) - .andExpect(model().attributeHasErrors("owner")) - .andExpect(model().attributeHasFieldErrors("owner", "address")) - .andExpect(model().attributeHasFieldErrors("owner", "telephone")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); - } - - @Test - void testShowOwner() throws Exception { - mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)).andExpect(status().isOk()) - .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) - .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) - .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")))) - .andExpect(model().attribute("owner", hasProperty("pets", not(empty())))) - .andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher>() { - - @Override - public boolean matches(Object item) { - @SuppressWarnings("unchecked") - List pets = (List) item; - Pet pet = pets.get(0); - if (pet.getVisits().isEmpty()) { - return false; - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText("Max did not have any visits"); - } - }))).andExpect(view().name("owners/ownerDetails")); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.owner; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; + +import org.assertj.core.util.Lists; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.samples.petclinic.visit.Visit; +import org.springframework.samples.petclinic.visit.VisitRepository; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.mockito.BDDMockito.given; +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; + +/** + * Test class for {@link OwnerController} + * + * @author Colin But + */ +@WebMvcTest(OwnerController.class) +class OwnerControllerTests { + + private static final int TEST_OWNER_ID = 1; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private OwnerRepository owners; + + @MockBean + private VisitRepository visits; + + private Owner george; + + @BeforeEach + void setup() { + 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.setId(1); + max.setType(dog); + max.setName("Max"); + max.setBirthDate(LocalDate.now()); + george.setPetsInternal(Collections.singleton(max)); + given(this.owners.findById(TEST_OWNER_ID)).willReturn(george); + Visit visit = new Visit(); + visit.setDate(LocalDate.now()); + given(this.visits.findByPetId(max.getId())).willReturn(Collections.singletonList(visit)); + } + + @Test + void testInitCreationForm() throws Exception { + mockMvc.perform(get("/owners/new")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); + } + + @Test + void testProcessCreationFormSuccess() throws Exception { + mockMvc.perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs") + .param("address", "123 Caramel Street").param("city", "London").param("telephone", "01316761638")) + .andExpect(status().is3xxRedirection()); + } + + @Test + void testProcessCreationFormHasErrors() throws Exception { + mockMvc.perform( + post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London")) + .andExpect(status().isOk()).andExpect(model().attributeHasErrors("owner")) + .andExpect(model().attributeHasFieldErrors("owner", "address")) + .andExpect(model().attributeHasFieldErrors("owner", "telephone")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); + } + + @Test + void testInitFindForm() throws Exception { + mockMvc.perform(get("/owners/find")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) + .andExpect(view().name("owners/findOwners")); + } + + @Test + void testProcessFindFormSuccess() throws Exception { + given(this.owners.findByLastName("")).willReturn(Lists.newArrayList(george, new Owner())); + mockMvc.perform(get("/owners")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList")); + } + + @Test + void testProcessFindFormByLastName() throws Exception { + given(this.owners.findByLastName(george.getLastName())).willReturn(Lists.newArrayList(george)); + mockMvc.perform(get("/owners").param("lastName", "Franklin")).andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID)); + } + + @Test + void testProcessFindFormNoOwnersFound() throws Exception { + mockMvc.perform(get("/owners").param("lastName", "Unknown Surname")).andExpect(status().isOk()) + .andExpect(model().attributeHasFieldErrors("owner", "lastName")) + .andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound")) + .andExpect(view().name("owners/findOwners")); + } + + @Test + void testInitUpdateOwnerForm() throws Exception { + mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)).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("address", is("110 W. Liberty St.")))) + .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) + .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); + } + + @Test + void testProcessUpdateOwnerFormSuccess() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") + .param("lastName", "Bloggs").param("address", "123 Caramel Street").param("city", "London") + .param("telephone", "01616291589")).andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); + } + + @Test + void testProcessUpdateOwnerFormHasErrors() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") + .param("lastName", "Bloggs").param("city", "London")).andExpect(status().isOk()) + .andExpect(model().attributeHasErrors("owner")) + .andExpect(model().attributeHasFieldErrors("owner", "address")) + .andExpect(model().attributeHasFieldErrors("owner", "telephone")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); + } + + @Test + void testShowOwner() throws Exception { + mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)).andExpect(status().isOk()) + .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) + .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) + .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")))) + .andExpect(model().attribute("owner", hasProperty("pets", not(empty())))) + .andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher>() { + + @Override + public boolean matches(Object item) { + @SuppressWarnings("unchecked") + List pets = (List) item; + Pet pet = pets.get(0); + if (pet.getVisits().isEmpty()) { + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("Max did not have any visits"); + } + }))).andExpect(view().name("owners/ownerDetails")); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java index 47c444a78..134457aa8 100755 --- a/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java @@ -1,113 +1,113 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.owner; - -import static org.mockito.BDDMockito.given; -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 org.assertj.core.util.Lists; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -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.context.annotation.ComponentScan; -import org.springframework.context.annotation.FilterType; -import org.springframework.test.web.servlet.MockMvc; - -/** - * Test class for the {@link PetController} - * - * @author Colin But - */ -@WebMvcTest(value = PetController.class, - includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) -class PetControllerTests { - - private static final int TEST_OWNER_ID = 1; - - private static final int TEST_PET_ID = 1; - - @Autowired - private MockMvc mockMvc; - - @MockBean - private PetRepository pets; - - @MockBean - private OwnerRepository owners; - - @BeforeEach - void setup() { - PetType cat = new PetType(); - cat.setId(3); - cat.setName("hamster"); - given(this.pets.findPetTypes()).willReturn(Lists.newArrayList(cat)); - given(this.owners.findById(TEST_OWNER_ID)).willReturn(new Owner()); - given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet()); - - } - - @Test - void testInitCreationForm() throws Exception { - mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")).andExpect(model().attributeExists("pet")); - } - - @Test - void testProcessCreationFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") - .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); - } - - @Test - void testProcessCreationFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty").param("birthDate", - "2015-02-12")).andExpect(model().attributeHasNoErrors("owner")) - .andExpect(model().attributeHasErrors("pet")).andExpect(model().attributeHasFieldErrors("pet", "type")) - .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")); - } - - @Test - void testInitUpdateForm() throws Exception { - mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID)) - .andExpect(status().isOk()).andExpect(model().attributeExists("pet")) - .andExpect(view().name("pets/createOrUpdatePetForm")); - } - - @Test - void testProcessUpdateFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") - .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); - } - - @Test - void testProcessUpdateFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") - .param("birthDate", "2015/02/12")).andExpect(model().attributeHasNoErrors("owner")) - .andExpect(model().attributeHasErrors("pet")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.owner; + +import static org.mockito.BDDMockito.given; +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 org.assertj.core.util.Lists; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.test.web.servlet.MockMvc; + +/** + * Test class for the {@link PetController} + * + * @author Colin But + */ +@WebMvcTest(value = PetController.class, + includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) +class PetControllerTests { + + private static final int TEST_OWNER_ID = 1; + + private static final int TEST_PET_ID = 1; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private PetRepository pets; + + @MockBean + private OwnerRepository owners; + + @BeforeEach + void setup() { + PetType cat = new PetType(); + cat.setId(3); + cat.setName("hamster"); + given(this.pets.findPetTypes()).willReturn(Lists.newArrayList(cat)); + given(this.owners.findById(TEST_OWNER_ID)).willReturn(new Owner()); + given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet()); + + } + + @Test + void testInitCreationForm() throws Exception { + mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)).andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")).andExpect(model().attributeExists("pet")); + } + + @Test + void testProcessCreationFormSuccess() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") + .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); + } + + @Test + void testProcessCreationFormHasErrors() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty").param("birthDate", + "2015-02-12")).andExpect(model().attributeHasNoErrors("owner")) + .andExpect(model().attributeHasErrors("pet")).andExpect(model().attributeHasFieldErrors("pet", "type")) + .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")).andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")); + } + + @Test + void testInitUpdateForm() throws Exception { + mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID)) + .andExpect(status().isOk()).andExpect(model().attributeExists("pet")) + .andExpect(view().name("pets/createOrUpdatePetForm")); + } + + @Test + void testProcessUpdateFormSuccess() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") + .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); + } + + @Test + void testProcessUpdateFormHasErrors() throws Exception { + mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") + .param("birthDate", "2015/02/12")).andExpect(model().attributeHasNoErrors("owner")) + .andExpect(model().attributeHasErrors("pet")).andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/owner/PetTypeFormatterTests.java b/src/test/java/org/springframework/samples/petclinic/owner/PetTypeFormatterTests.java index adb96b69d..99d07ade4 100644 --- a/src/test/java/org/springframework/samples/petclinic/owner/PetTypeFormatterTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/PetTypeFormatterTests.java @@ -1,95 +1,95 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.owner; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test class for {@link PetTypeFormatter} - * - * @author Colin But - */ -@ExtendWith(MockitoExtension.class) -class PetTypeFormatterTests { - - @Mock - private PetRepository pets; - - private PetTypeFormatter petTypeFormatter; - - @BeforeEach - void setup() { - this.petTypeFormatter = new PetTypeFormatter(pets); - } - - @Test - void testPrint() { - PetType petType = new PetType(); - petType.setName("Hamster"); - String petTypeName = this.petTypeFormatter.print(petType, Locale.ENGLISH); - 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"); - } - - @Test - void shouldThrowParseException() throws ParseException { - given(this.pets.findPetTypes()).willReturn(makePetTypes()); - 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 makePetTypes() { - List petTypes = new ArrayList<>(); - petTypes.add(new PetType() { - { - setName("Dog"); - } - }); - petTypes.add(new PetType() { - { - setName("Bird"); - } - }); - return petTypes; - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.owner; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +/** + * Test class for {@link PetTypeFormatter} + * + * @author Colin But + */ +@ExtendWith(MockitoExtension.class) +class PetTypeFormatterTests { + + @Mock + private PetRepository pets; + + private PetTypeFormatter petTypeFormatter; + + @BeforeEach + void setup() { + this.petTypeFormatter = new PetTypeFormatter(pets); + } + + @Test + void testPrint() { + PetType petType = new PetType(); + petType.setName("Hamster"); + String petTypeName = this.petTypeFormatter.print(petType, Locale.ENGLISH); + 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"); + } + + @Test + void shouldThrowParseException() throws ParseException { + given(this.pets.findPetTypes()).willReturn(makePetTypes()); + 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 makePetTypes() { + List petTypes = new ArrayList<>(); + petTypes.add(new PetType() { + { + setName("Dog"); + } + }); + petTypes.add(new PetType() { + { + setName("Bird"); + } + }); + return petTypes; + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java index 84bee72df..137877952 100644 --- a/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java @@ -1,78 +1,78 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.owner; - -import static org.mockito.BDDMockito.given; -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 org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -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.samples.petclinic.visit.VisitRepository; -import org.springframework.test.web.servlet.MockMvc; - -/** - * Test class for {@link VisitController} - * - * @author Colin But - */ -@WebMvcTest(VisitController.class) -class VisitControllerTests { - - private static final int TEST_PET_ID = 1; - - @Autowired - private MockMvc mockMvc; - - @MockBean - private VisitRepository visits; - - @MockBean - private PetRepository pets; - - @BeforeEach - void init() { - given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet()); - } - - @Test - void testInitNewVisitForm() throws Exception { - mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID)).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdateVisitForm")); - } - - @Test - void testProcessNewVisitFormSuccess() throws Exception { - mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George") - .param("description", "Visit Description")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); - } - - @Test - void testProcessNewVisitFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George")) - .andExpect(model().attributeHasErrors("visit")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdateVisitForm")); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.owner; + +import static org.mockito.BDDMockito.given; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.samples.petclinic.visit.VisitRepository; +import org.springframework.test.web.servlet.MockMvc; + +/** + * Test class for {@link VisitController} + * + * @author Colin But + */ +@WebMvcTest(VisitController.class) +class VisitControllerTests { + + private static final int TEST_PET_ID = 1; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VisitRepository visits; + + @MockBean + private PetRepository pets; + + @BeforeEach + void init() { + given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet()); + } + + @Test + void testInitNewVisitForm() throws Exception { + mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID)).andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdateVisitForm")); + } + + @Test + void testProcessNewVisitFormSuccess() throws Exception { + mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George") + .param("description", "Visit Description")).andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); + } + + @Test + void testProcessNewVisitFormHasErrors() throws Exception { + mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George")) + .andExpect(model().attributeHasErrors("visit")).andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdateVisitForm")); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/service/ClinicServiceTests.java b/src/test/java/org/springframework/samples/petclinic/service/ClinicServiceTests.java index a7f3d9d24..f8f297b6f 100644 --- a/src/test/java/org/springframework/samples/petclinic/service/ClinicServiceTests.java +++ b/src/test/java/org/springframework/samples/petclinic/service/ClinicServiceTests.java @@ -1,227 +1,227 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.service; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.LocalDate; -import java.util.Collection; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.samples.petclinic.owner.Owner; -import org.springframework.samples.petclinic.owner.OwnerRepository; -import org.springframework.samples.petclinic.owner.Pet; -import org.springframework.samples.petclinic.owner.PetRepository; -import org.springframework.samples.petclinic.owner.PetType; -import org.springframework.samples.petclinic.vet.Vet; -import org.springframework.samples.petclinic.vet.VetRepository; -import org.springframework.samples.petclinic.visit.Visit; -import org.springframework.samples.petclinic.visit.VisitRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Integration test of the Service and the Repository layer. - *

- * ClinicServiceSpringDataJpaTests 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 {@link - * ClinicServiceTests#clinicService clinicService} 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 - * @author Juergen Hoeller - * @author Sam Brannen - * @author Michael Isvy - * @author Dave Syer - */ -@DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class)) -class ClinicServiceTests { - - @Autowired - protected OwnerRepository owners; - - @Autowired - protected PetRepository pets; - - @Autowired - protected VisitRepository visits; - - @Autowired - protected VetRepository vets; - - @Test - void shouldFindOwnersByLastName() { - Collection owners = this.owners.findByLastName("Davis"); - assertThat(owners).hasSize(2); - - owners = this.owners.findByLastName("Daviss"); - assertThat(owners).isEmpty(); - } - - @Test - void shouldFindSingleOwnerWithPet() { - Owner owner = this.owners.findById(1); - 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"); - } - - @Test - @Transactional - void shouldInsertOwner() { - Collection owners = this.owners.findByLastName("Schultz"); - 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.owners.save(owner); - assertThat(owner.getId().longValue()).isNotEqualTo(0); - - owners = this.owners.findByLastName("Schultz"); - assertThat(owners.size()).isEqualTo(found + 1); - } - - @Test - @Transactional - void shouldUpdateOwner() { - Owner owner = this.owners.findById(1); - String oldLastName = owner.getLastName(); - String newLastName = oldLastName + "X"; - - owner.setLastName(newLastName); - this.owners.save(owner); - - // retrieving new name from database - owner = this.owners.findById(1); - assertThat(owner.getLastName()).isEqualTo(newLastName); - } - - @Test - void shouldFindPetWithCorrectId() { - Pet pet7 = this.pets.findById(7); - assertThat(pet7.getName()).startsWith("Samantha"); - assertThat(pet7.getOwner().getFirstName()).isEqualTo("Jean"); - - } - - @Test - void shouldFindAllPetTypes() { - Collection petTypes = this.pets.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 - void shouldInsertPetIntoDatabaseAndGenerateId() { - Owner owner6 = this.owners.findById(6); - int found = owner6.getPets().size(); - - Pet pet = new Pet(); - pet.setName("bowser"); - Collection types = this.pets.findPetTypes(); - pet.setType(EntityUtils.getById(types, PetType.class, 2)); - pet.setBirthDate(LocalDate.now()); - owner6.addPet(pet); - assertThat(owner6.getPets().size()).isEqualTo(found + 1); - - this.pets.save(pet); - this.owners.save(owner6); - - owner6 = this.owners.findById(6); - assertThat(owner6.getPets().size()).isEqualTo(found + 1); - // checks that id has been generated - assertThat(pet.getId()).isNotNull(); - } - - @Test - @Transactional - void shouldUpdatePetName() throws Exception { - Pet pet7 = this.pets.findById(7); - String oldName = pet7.getName(); - - String newName = oldName + "X"; - pet7.setName(newName); - this.pets.save(pet7); - - pet7 = this.pets.findById(7); - assertThat(pet7.getName()).isEqualTo(newName); - } - - @Test - void shouldFindVets() { - Collection vets = this.vets.findAll(); - - 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 - void shouldAddNewVisitForPet() { - Pet pet7 = this.pets.findById(7); - int found = pet7.getVisits().size(); - Visit visit = new Visit(); - pet7.addVisit(visit); - visit.setDescription("test"); - this.visits.save(visit); - this.pets.save(pet7); - - pet7 = this.pets.findById(7); - assertThat(pet7.getVisits().size()).isEqualTo(found + 1); - assertThat(visit.getId()).isNotNull(); - } - - @Test - void shouldFindVisitsByPetId() throws Exception { - Collection visits = this.visits.findByPetId(7); - assertThat(visits).hasSize(2); - Visit[] visitArr = visits.toArray(new Visit[visits.size()]); - assertThat(visitArr[0].getDate()).isNotNull(); - assertThat(visitArr[0].getPetId()).isEqualTo(7); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDate; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.samples.petclinic.owner.Owner; +import org.springframework.samples.petclinic.owner.OwnerRepository; +import org.springframework.samples.petclinic.owner.Pet; +import org.springframework.samples.petclinic.owner.PetRepository; +import org.springframework.samples.petclinic.owner.PetType; +import org.springframework.samples.petclinic.vet.Vet; +import org.springframework.samples.petclinic.vet.VetRepository; +import org.springframework.samples.petclinic.visit.Visit; +import org.springframework.samples.petclinic.visit.VisitRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration test of the Service and the Repository layer. + *

+ * ClinicServiceSpringDataJpaTests 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 {@link + * ClinicServiceTests#clinicService clinicService} 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 + * @author Juergen Hoeller + * @author Sam Brannen + * @author Michael Isvy + * @author Dave Syer + */ +@DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class)) +class ClinicServiceTests { + + @Autowired + protected OwnerRepository owners; + + @Autowired + protected PetRepository pets; + + @Autowired + protected VisitRepository visits; + + @Autowired + protected VetRepository vets; + + @Test + void shouldFindOwnersByLastName() { + Collection owners = this.owners.findByLastName("Davis"); + assertThat(owners).hasSize(2); + + owners = this.owners.findByLastName("Daviss"); + assertThat(owners).isEmpty(); + } + + @Test + void shouldFindSingleOwnerWithPet() { + Owner owner = this.owners.findById(1); + 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"); + } + + @Test + @Transactional + void shouldInsertOwner() { + Collection owners = this.owners.findByLastName("Schultz"); + 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.owners.save(owner); + assertThat(owner.getId().longValue()).isNotEqualTo(0); + + owners = this.owners.findByLastName("Schultz"); + assertThat(owners.size()).isEqualTo(found + 1); + } + + @Test + @Transactional + void shouldUpdateOwner() { + Owner owner = this.owners.findById(1); + String oldLastName = owner.getLastName(); + String newLastName = oldLastName + "X"; + + owner.setLastName(newLastName); + this.owners.save(owner); + + // retrieving new name from database + owner = this.owners.findById(1); + assertThat(owner.getLastName()).isEqualTo(newLastName); + } + + @Test + void shouldFindPetWithCorrectId() { + Pet pet7 = this.pets.findById(7); + assertThat(pet7.getName()).startsWith("Samantha"); + assertThat(pet7.getOwner().getFirstName()).isEqualTo("Jean"); + + } + + @Test + void shouldFindAllPetTypes() { + Collection petTypes = this.pets.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 + void shouldInsertPetIntoDatabaseAndGenerateId() { + Owner owner6 = this.owners.findById(6); + int found = owner6.getPets().size(); + + Pet pet = new Pet(); + pet.setName("bowser"); + Collection types = this.pets.findPetTypes(); + pet.setType(EntityUtils.getById(types, PetType.class, 2)); + pet.setBirthDate(LocalDate.now()); + owner6.addPet(pet); + assertThat(owner6.getPets().size()).isEqualTo(found + 1); + + this.pets.save(pet); + this.owners.save(owner6); + + owner6 = this.owners.findById(6); + assertThat(owner6.getPets().size()).isEqualTo(found + 1); + // checks that id has been generated + assertThat(pet.getId()).isNotNull(); + } + + @Test + @Transactional + void shouldUpdatePetName() throws Exception { + Pet pet7 = this.pets.findById(7); + String oldName = pet7.getName(); + + String newName = oldName + "X"; + pet7.setName(newName); + this.pets.save(pet7); + + pet7 = this.pets.findById(7); + assertThat(pet7.getName()).isEqualTo(newName); + } + + @Test + void shouldFindVets() { + Collection vets = this.vets.findAll(); + + 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 + void shouldAddNewVisitForPet() { + Pet pet7 = this.pets.findById(7); + int found = pet7.getVisits().size(); + Visit visit = new Visit(); + pet7.addVisit(visit); + visit.setDescription("test"); + this.visits.save(visit); + this.pets.save(pet7); + + pet7 = this.pets.findById(7); + assertThat(pet7.getVisits().size()).isEqualTo(found + 1); + assertThat(visit.getId()).isNotNull(); + } + + @Test + void shouldFindVisitsByPetId() throws Exception { + Collection visits = this.visits.findByPetId(7); + assertThat(visits).hasSize(2); + Visit[] visitArr = visits.toArray(new Visit[visits.size()]); + assertThat(visitArr[0].getDate()).isNotNull(); + assertThat(visitArr[0].getPetId()).isEqualTo(7); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/service/EntityUtils.java b/src/test/java/org/springframework/samples/petclinic/service/EntityUtils.java index ca8bc41fc..39a10c2f7 100644 --- a/src/test/java/org/springframework/samples/petclinic/service/EntityUtils.java +++ b/src/test/java/org/springframework/samples/petclinic/service/EntityUtils.java @@ -1,53 +1,53 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.service; - -import java.util.Collection; - -import org.springframework.orm.ObjectRetrievalFailureException; -import org.springframework.samples.petclinic.model.BaseEntity; - -/** - * Utility methods for handling entities. Separate from the BaseEntity class mainly - * because of dependency on the ORM-associated ObjectRetrievalFailureException. - * - * @author Juergen Hoeller - * @author Sam Brannen - * @see org.springframework.samples.petclinic.model.BaseEntity - * @since 29.10.2003 - */ -public abstract class EntityUtils { - - /** - * Look up the entity of the given class with the given id in the given collection. - * @param entities the collection to search - * @param entityClass the entity class to look up - * @param entityId the entity id to look up - * @return the found entity - * @throws ObjectRetrievalFailureException if the entity was not found - */ - public static T getById(Collection entities, Class entityClass, int entityId) - throws ObjectRetrievalFailureException { - for (T entity : entities) { - if (entity.getId() == entityId && entityClass.isInstance(entity)) { - return entity; - } - } - throw new ObjectRetrievalFailureException(entityClass, entityId); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.service; + +import java.util.Collection; + +import org.springframework.orm.ObjectRetrievalFailureException; +import org.springframework.samples.petclinic.model.BaseEntity; + +/** + * Utility methods for handling entities. Separate from the BaseEntity class mainly + * because of dependency on the ORM-associated ObjectRetrievalFailureException. + * + * @author Juergen Hoeller + * @author Sam Brannen + * @see org.springframework.samples.petclinic.model.BaseEntity + * @since 29.10.2003 + */ +public abstract class EntityUtils { + + /** + * Look up the entity of the given class with the given id in the given collection. + * @param entities the collection to search + * @param entityClass the entity class to look up + * @param entityId the entity id to look up + * @return the found entity + * @throws ObjectRetrievalFailureException if the entity was not found + */ + public static T getById(Collection entities, Class entityClass, int entityId) + throws ObjectRetrievalFailureException { + for (T entity : entities) { + if (entity.getId() == entityId && entityClass.isInstance(entity)) { + return entity; + } + } + throw new ObjectRetrievalFailureException(entityClass, entityId); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java index 6bafc7499..39eb66d56 100644 --- a/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java @@ -1,51 +1,51 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.system; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.test.web.servlet.MockMvc; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; -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; - -/** - * Test class for {@link CrashController} - * - * @author Colin But - */ -// Waiting https://github.com/spring-projects/spring-boot/issues/5574 -@Disabled -@WebMvcTest(controllers = CrashController.class) -class CrashControllerTests { - - @Autowired - private MockMvc mockMvc; - - @Test - void testTriggerException() throws Exception { - mockMvc.perform(get("/oups")).andExpect(view().name("exception")) - .andExpect(model().attributeExists("exception")).andExpect(forwardedUrl("exception")) - .andExpect(status().isOk()); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.system; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +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; + +/** + * Test class for {@link CrashController} + * + * @author Colin But + */ +// Waiting https://github.com/spring-projects/spring-boot/issues/5574 +@Disabled +@WebMvcTest(controllers = CrashController.class) +class CrashControllerTests { + + @Autowired + private MockMvc mockMvc; + + @Test + void testTriggerException() throws Exception { + mockMvc.perform(get("/oups")).andExpect(view().name("exception")) + .andExpect(model().attributeExists("exception")).andExpect(forwardedUrl("exception")) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java b/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java index fd537bee2..0d8646b5d 100644 --- a/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java @@ -1,80 +1,80 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.samples.petclinic.vet; - -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.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.assertj.core.util.Lists; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -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.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; - -/** - * Test class for the {@link VetController} - */ -@WebMvcTest(VetController.class) -class VetControllerTests { - - @Autowired - private MockMvc mockMvc; - - @MockBean - private VetRepository vets; - - @BeforeEach - void setup() { - Vet james = new Vet(); - james.setFirstName("James"); - james.setLastName("Carter"); - james.setId(1); - 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); - given(this.vets.findAll()).willReturn(Lists.newArrayList(james, helen)); - } - - @Test - void testShowVetListHtml() throws Exception { - mockMvc.perform(get("/vets.html")).andExpect(status().isOk()).andExpect(model().attributeExists("vets")) - .andExpect(view().name("vets/vetList")); - } - - @Test - void testShowResourcesVetList() throws Exception { - ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - actions.andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.vetList[0].id").value(1)); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.vet; + +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.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; + +/** + * Test class for the {@link VetController} + */ +@WebMvcTest(VetController.class) +class VetControllerTests { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VetRepository vets; + + @BeforeEach + void setup() { + Vet james = new Vet(); + james.setFirstName("James"); + james.setLastName("Carter"); + james.setId(1); + 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); + given(this.vets.findAll()).willReturn(Lists.newArrayList(james, helen)); + } + + @Test + void testShowVetListHtml() throws Exception { + mockMvc.perform(get("/vets.html")).andExpect(status().isOk()).andExpect(model().attributeExists("vets")) + .andExpect(view().name("vets/vetList")); + } + + @Test + void testShowResourcesVetList() throws Exception { + ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + actions.andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.vetList[0].id").value(1)); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/vet/VetTests.java b/src/test/java/org/springframework/samples/petclinic/vet/VetTests.java index d8df78b85..e9239b4d8 100644 --- a/src/test/java/org/springframework/samples/petclinic/vet/VetTests.java +++ b/src/test/java/org/springframework/samples/petclinic/vet/VetTests.java @@ -1,40 +1,40 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.samples.petclinic.vet; - -import org.junit.jupiter.api.Test; -import org.springframework.util.SerializationUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - */ -class VetTests { - - @Test - void testSerialization() { - Vet vet = new Vet(); - vet.setFirstName("Zaphod"); - vet.setLastName("Beeblebrox"); - vet.setId(123); - 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()); - } - -} +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.samples.petclinic.vet; + +import org.junit.jupiter.api.Test; +import org.springframework.util.SerializationUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Dave Syer + */ +class VetTests { + + @Test + void testSerialization() { + Vet vet = new Vet(); + vet.setFirstName("Zaphod"); + vet.setLastName("Beeblebrox"); + vet.setId(123); + 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()); + } + +}