Merge pull request #2 from gordonad/master

Build and logging improvements
This commit is contained in:
michaelisvy 2013-02-19 16:59:04 -08:00
commit ed116de007
90 changed files with 3393 additions and 2999 deletions

896
pom.xml

File diff suppressed because it is too large Load diff

View file

@ -21,15 +21,15 @@ 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.
* 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 {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;

View file

@ -20,8 +20,8 @@ import javax.persistence.MappedSuperclass;
/**
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>.
* Used as a base class for objects needing these properties.
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>. Used as a base class for objects
* needing these properties.
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -29,7 +29,7 @@ import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class NamedEntity extends BaseEntity {
@Column(name="name")
@Column(name = "name")
private String name;

View file

@ -15,24 +15,15 @@
*/
package org.springframework.samples.petclinic.model;
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 org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.support.MutableSortDefinition;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.core.style.ToStringCreator;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import java.util.*;
/**
* Simple JavaBean domain object representing an owner.
*
@ -41,21 +32,23 @@ import org.springframework.core.style.ToStringCreator;
* @author Sam Brannen
* @author Michael Isvy
*/
@Entity @Table(name="owners")
@Entity
@Table(name = "owners")
public class Owner extends Person {
@Column(name="address")
@Column(name = "address")
@NotEmpty
private String address;
@Column(name="city")
@Column(name = "city")
@NotEmpty
private String city;
@Column(name="telephone")
@NotEmpty @Digits(fraction = 0, integer = 10)
@Column(name = "telephone")
@NotEmpty
@Digits(fraction = 0, integer = 10)
private String telephone;
@OneToMany(cascade=CascadeType.ALL, mappedBy="owner")
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Pet> pets;

View file

@ -15,11 +15,11 @@
*/
package org.springframework.samples.petclinic.model;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Simple JavaBean domain object representing an person.
*
@ -28,11 +28,11 @@ import org.hibernate.validator.constraints.NotEmpty;
@MappedSuperclass
public class Person extends BaseEntity {
@Column(name="first_name")
@Column(name = "first_name")
@NotEmpty
protected String firstName;
@Column(name="last_name")
@Column(name = "last_name")
@NotEmpty
protected String lastName;
@ -53,5 +53,4 @@ public class Person extends BaseEntity {
}
}

View file

@ -15,27 +15,15 @@
*/
package org.springframework.samples.petclinic.model;
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.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.beans.support.MutableSortDefinition;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.*;
/**
* Simple business object representing a pet.
*
@ -43,12 +31,13 @@ import org.springframework.format.annotation.DateTimeFormat;
* @author Juergen Hoeller
* @author Sam Brannen
*/
@Entity @Table(name="pets")
@Entity
@Table(name = "pets")
public class Pet extends NamedEntity {
@Column(name="birth_date")
@Column(name = "birth_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(pattern="yyyy/MM/dd")
@DateTimeFormat(pattern = "yyyy/MM/dd")
private DateTime birthDate;
@ManyToOne
@ -59,7 +48,7 @@ public class Pet extends NamedEntity {
@JoinColumn(name = "owner_id")
private Owner owner;
@OneToMany(cascade=CascadeType.ALL, mappedBy="pet", fetch=FetchType.EAGER)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pet", fetch = FetchType.EAGER)
private Set<Visit> visits;

View file

@ -21,7 +21,8 @@ import javax.persistence.Table;
/**
* @author Juergen Hoeller
*/
@Entity @Table(name="types")
@Entity
@Table(name = "types")
public class PetType extends NamedEntity {
}

View file

@ -23,7 +23,8 @@ import javax.persistence.Table;
*
* @author Juergen Hoeller
*/
@Entity @Table(name="specialties")
@Entity
@Table(name = "specialties")
public class Specialty extends NamedEntity {
}

View file

@ -15,23 +15,13 @@
*/
package org.springframework.samples.petclinic.model;
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 javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import java.util.*;
/**
* Simple JavaBean domain object representing a veterinarian.
*
@ -40,12 +30,13 @@ import org.springframework.beans.support.PropertyComparator;
* @author Sam Brannen
* @author Arjen Poutsma
*/
@Entity @Table(name="vets")
@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"))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"),
inverseJoinColumns = @JoinColumn(name = "specialty_id"))
private Set<Specialty> specialties;

View file

@ -16,15 +16,14 @@
*/
package org.springframework.samples.petclinic.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
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}.
* 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
*/

View file

@ -15,84 +15,101 @@
*/
package org.springframework.samples.petclinic.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.DateTime;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
/**
* Simple JavaBean domain object representing a visit.
*
* @author Ken Krebs
*/
@Entity @Table(name="visits")
@Entity
@Table(name = "visits")
public class Visit extends BaseEntity {
/** Holds value of property date. */
@Column(name="visit_date")
/**
* Holds value of property date.
*/
@Column(name = "visit_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(pattern="yyyy/MM/dd")
@DateTimeFormat(pattern = "yyyy/MM/dd")
private DateTime date;
/** Holds value of property description. */
/**
* Holds value of property description.
*/
@NotEmpty
@Column(name="description")
@Column(name = "description")
private String description;
/** Holds value of property pet. */
/**
* Holds value of property pet.
*/
@ManyToOne
@JoinColumn(name = "pet_id")
private Pet pet;
/** Creates a new instance of Visit for the current date */
/**
* Creates a new instance of Visit for the current date
*/
public Visit() {
this.date = new DateTime();
}
/** Getter for property date.
/**
* Getter for property date.
*
* @return Value of property date.
*/
public DateTime getDate() {
return this.date;
}
/** Setter for property date.
/**
* Setter for property date.
*
* @param date New value of property date.
*/
public void setDate(DateTime date) {
this.date = date;
}
/** Getter for property description.
/**
* Getter for property description.
*
* @return Value of property description.
*/
public String getDescription() {
return this.description;
}
/** Setter for property description.
/**
* Setter for property description.
*
* @param description New value of property description.
*/
public void setDescription(String description) {
this.description = description;
}
/** Getter for property pet.
/**
* Getter for property pet.
*
* @return Value of property pet.
*/
public Pet getPet() {
return this.pet;
}
/** Setter for property pet.
/**
* Setter for property pet.
*
* @param pet New value of property pet.
*/
public void setPet(Pet pet) {

View file

@ -30,17 +30,15 @@
*/
package org.springframework.samples.petclinic.repository;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Owner;
import java.util.Collection;
/**
* Repository class for <code>Owner</code> domain objects
* All method names are compliant with Spring Data naming conventions so this interface can easily be
* extended for Spring Data
* See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
* Repository class for <code>Owner</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -50,25 +48,29 @@ import org.springframework.samples.petclinic.model.Owner;
public interface OwnerRepository {
/**
* Retrieve <code>Owner</code>s from the data store by last name,
* returning all owners whose last name <i>starts</i> with the given name.
* Retrieve <code>Owner</code>s from the data store by last name, returning all owners whose last name <i>starts</i>
* with the given name.
*
* @param lastName Value to search for
* @return a <code>Collection</code> of matching <code>Owner</code>s
* (or an empty <code>Collection</code> if none found)
* @return a <code>Collection</code> of matching <code>Owner</code>s (or an empty <code>Collection</code> if none
* found)
*/
Collection<Owner> findByLastName(String lastName) throws DataAccessException;
/**
* Retrieve an <code>Owner</code> from the data store by id.
*
* @param id the id to search for
* @return the <code>Owner</code> if found
* @throws org.springframework.dao.DataRetrievalFailureException if not found
* @throws org.springframework.dao.DataRetrievalFailureException
* if not found
*/
Owner findById(int id) throws DataAccessException;
/**
* Save an <code>Owner</code> to the data store, either inserting or updating it.
*
* @param owner the <code>Owner</code> to save
* @see BaseEntity#isNew
*/

View file

@ -15,18 +15,16 @@
*/
package org.springframework.samples.petclinic.repository;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import java.util.List;
/**
* Repository class for <code>Pet</code> domain objects
* All method names are compliant with Spring Data naming conventions so this interface can easily be
* extended for Spring Data
* See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
* Repository class for <code>Pet</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -37,20 +35,24 @@ public interface PetRepository {
/**
* Retrieve all <code>PetType</code>s from the data store.
*
* @return a <code>Collection</code> of <code>PetType</code>s
*/
List<PetType> findPetTypes() throws DataAccessException;
/**
* Retrieve a <code>Pet</code> from the data store by id.
*
* @param id the id to search for
* @return the <code>Pet</code> if found
* @throws org.springframework.dao.DataRetrievalFailureException if not found
* @throws org.springframework.dao.DataRetrievalFailureException
* if not found
*/
Pet findById(int id) throws DataAccessException;
/**
* Save a <code>Pet</code> to the data store, either inserting or updating it.
*
* @param pet the <code>Pet</code> to save
* @see BaseEntity#isNew
*/

View file

@ -15,16 +15,14 @@
*/
package org.springframework.samples.petclinic.repository;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.Vet;
import java.util.Collection;
/**
* Repository class for <code>Vet</code> domain objects
* All method names are compliant with Spring Data naming conventions so this interface can easily be
* extended for Spring Data
* See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
* Repository class for <code>Vet</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -35,6 +33,7 @@ public interface VetRepository {
/**
* Retrieve all <code>Vet</code>s from the data store.
*
* @return a <code>Collection</code> of <code>Vet</code>s
*/
Collection<Vet> findAll() throws DataAccessException;

View file

@ -15,17 +15,15 @@
*/
package org.springframework.samples.petclinic.repository;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Visit;
import java.util.List;
/**
* Repository class for <code>Visit</code> domain objects
* All method names are compliant with Spring Data naming conventions so this interface can easily be
* extended for Spring Data
* See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
* Repository class for <code>Visit</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -36,6 +34,7 @@ public interface VisitRepository {
/**
* Save a <code>Visit</code> to the data store, either inserting or updating it.
*
* @param visit the <code>Visit</code> to save
* @see BaseEntity#isNew
*/

View file

@ -15,13 +15,6 @@
*/
package org.springframework.samples.petclinic.repository.jdbc;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
@ -39,10 +32,15 @@ import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple JDBC-based implementation of the {@link OwnerRepository} interface.
*
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Rob Harrop
@ -73,17 +71,15 @@ public class JdbcOwnerRepositoryImpl implements OwnerRepository {
}
/**
* Loads {@link Owner Owners} from the data store by last name, returning
* all owners whose last name <i>starts</i> with the given name; also loads
* the {@link Pet Pets} and {@link Visit Visits} for the corresponding
* owners, if not already loaded.
* Loads {@link Owner Owners} from the data store by last name, returning all owners whose last name <i>starts</i> with
* the given name; also loads the {@link Pet Pets} and {@link Visit Visits} for the corresponding owners, if not
* already loaded.
*/
@Override
public Collection<Owner> findByLastName(String lastName) throws DataAccessException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("lastName", lastName+"%");
params.put("lastName", lastName + "%");
List<Owner> owners = this.namedParameterJdbcTemplate.query(
"SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE last_name like :lastName",
params,
@ -94,10 +90,10 @@ public class JdbcOwnerRepositoryImpl implements OwnerRepository {
}
/**
* Loads the {@link Owner} with the supplied <code>id</code>; also loads
* the {@link Pet Pets} and {@link Visit Visits} for the corresponding
* owner, if not already loaded.
* Loads the {@link Owner} with the supplied <code>id</code>; also loads the {@link Pet Pets} and {@link Visit Visits}
* for the corresponding owner, if not already loaded.
*/
@Override
public Owner findById(int id) throws DataAccessException {
Owner owner;
try {
@ -108,8 +104,7 @@ public class JdbcOwnerRepositoryImpl implements OwnerRepository {
params,
ParameterizedBeanPropertyRowMapper.newInstance(Owner.class)
);
}
catch (EmptyResultDataAccessException ex) {
} catch (EmptyResultDataAccessException ex) {
throw new ObjectRetrievalFailureException(Owner.class, new Integer(id));
}
loadPetsAndVisits(owner);
@ -134,13 +129,13 @@ public class JdbcOwnerRepositoryImpl implements OwnerRepository {
}
}
@Override
public void save(Owner owner) throws DataAccessException {
BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
if (owner.isNew()) {
Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
owner.setId(newKey.intValue());
}
else {
} else {
this.namedParameterJdbcTemplate.update(
"UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
"city=:city, telephone=:telephone WHERE id=:id",
@ -150,13 +145,12 @@ public class JdbcOwnerRepositoryImpl implements OwnerRepository {
public Collection<PetType> getPetTypes() throws DataAccessException {
return this.namedParameterJdbcTemplate.query(
"SELECT id, name FROM types ORDER BY name", new HashMap<String,Object>(),
"SELECT id, name FROM types ORDER BY name", new HashMap<String, Object>(),
ParameterizedBeanPropertyRowMapper.newInstance(PetType.class));
}
/**
* Loads the {@link Pet} and {@link Visit} data for the supplied
* {@link List} of {@link Owner Owners}.
* Loads the {@link Pet} and {@link Visit} data for the supplied {@link List} of {@link Owner Owners}.
*
* @param owners the list of owners for whom the pet and visit data should be loaded
* @see #loadPetsAndVisits(Owner)

View file

@ -18,8 +18,8 @@ package org.springframework.samples.petclinic.repository.jdbc;
import org.springframework.samples.petclinic.model.Pet;
/**
* Subclass of Pet that carries temporary id properties which
* are only relevant for a JDBC implmentation of the ClinicService.
* Subclass of Pet that carries temporary id properties which are only relevant for a JDBC implmentation of the
* ClinicService.
*
* @author Juergen Hoeller
* @see JdbcClinicImpl

View file

@ -15,12 +15,6 @@
*/
package org.springframework.samples.petclinic.repository.jdbc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
@ -39,8 +33,12 @@ import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Rob Harrop
@ -72,14 +70,16 @@ public class JdbcPetRepositoryImpl implements PetRepository {
this.visitRepository = visitRepository;
}
@Override
public List<PetType> findPetTypes() throws DataAccessException {
Map<String, Object> params = new HashMap<String,Object>();
Map<String, Object> params = new HashMap<String, Object>();
return this.namedParameterJdbcTemplate.query(
"SELECT id, name FROM types ORDER BY name",
params,
ParameterizedBeanPropertyRowMapper.newInstance(PetType.class));
}
@Override
public Pet findById(int id) throws DataAccessException {
JdbcPet pet;
try {
@ -89,8 +89,7 @@ public class JdbcPetRepositoryImpl implements PetRepository {
"SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE id=:id",
params,
new JdbcPetRowMapper());
}
catch (EmptyResultDataAccessException ex) {
} catch (EmptyResultDataAccessException ex) {
throw new ObjectRetrievalFailureException(Pet.class, new Integer(id));
}
Owner owner = this.ownerRepository.findById(pet.getOwnerId());
@ -104,13 +103,13 @@ public class JdbcPetRepositoryImpl implements PetRepository {
return pet;
}
@Override
public void save(Pet pet) throws DataAccessException {
if (pet.isNew()) {
Number newKey = this.insertPet.executeAndReturnKey(
createPetParameterSource(pet));
pet.setId(newKey.intValue());
}
else {
} else {
this.namedParameterJdbcTemplate.update(
"UPDATE pets SET name=:name, birth_date=:birth_date, type_id=:type_id, " +
"owner_id=:owner_id WHERE id=:id",
@ -119,8 +118,7 @@ public class JdbcPetRepositoryImpl implements PetRepository {
}
/**
* Creates a {@link MapSqlParameterSource} based on data values from the
* supplied {@link Pet} instance.
* Creates a {@link MapSqlParameterSource} based on data values from the supplied {@link Pet} instance.
*/
private MapSqlParameterSource createPetParameterSource(Pet pet) {
return new MapSqlParameterSource()

View file

@ -15,19 +15,20 @@
*/
package org.springframework.samples.petclinic.repository.jdbc;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
/**
* {@link ParameterizedRowMapper} implementation mapping data from a
* {@link ResultSet} to the corresponding properties of the {@link JdbcPet} class.
* {@link ParameterizedRowMapper} implementation mapping data from a {@link ResultSet} to the corresponding properties
* of the {@link JdbcPet} class.
*/
class JdbcPetRowMapper implements ParameterizedRowMapper<JdbcPet> {
@Override
public JdbcPet mapRow(ResultSet rs, int rownum) throws SQLException {
JdbcPet pet = new JdbcPet();
pet.setId(rs.getInt("id"));

View file

@ -15,12 +15,6 @@
*/
package org.springframework.samples.petclinic.repository.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DataAccessException;
@ -33,10 +27,15 @@ import org.springframework.samples.petclinic.repository.VetRepository;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
*
* A simple JDBC-based implementation of the {@link VetRepository} interface.
* Uses @Cacheable to cache the result of the {@link findAll} method
* A simple JDBC-based implementation of the {@link VetRepository} interface. Uses @Cacheable to cache the result of the
* {@link findAll} method
*
* @author Ken Krebs
* @author Juergen Hoeller
@ -58,9 +57,11 @@ public class JdbcVetRepositoryImpl implements VetRepository {
/**
* Refresh the cache of Vets that the ClinicService is holding.
*
* @see org.springframework.samples.petclinic.model.service.ClinicService#findVets()
*/
@Cacheable(value="vets")
@Override
@Cacheable(value = "vets")
public Collection<Vet> findAll() throws DataAccessException {
List<Vet> vets = new ArrayList<Vet>();
// Retrieve the list of all vets.
@ -78,9 +79,11 @@ public class JdbcVetRepositoryImpl implements VetRepository {
final List<Integer> vetSpecialtiesIds = this.jdbcTemplate.query(
"SELECT specialty_id FROM vet_specialties WHERE vet_id=?",
new ParameterizedRowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet rs, int row) throws SQLException {
return Integer.valueOf(rs.getInt(1));
}},
}
},
vet.getId().intValue());
for (int specialtyId : vetSpecialtiesIds) {
Specialty specialty = EntityUtils.getById(specialties, Specialty.class, specialtyId);

View file

@ -15,13 +15,6 @@
*/
package org.springframework.samples.petclinic.repository.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import javax.sql.DataSource;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
@ -33,10 +26,15 @@ import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
/**
* A simple JDBC-based implementation of the {@link VisitRepository} interface.
*
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Rob Harrop
@ -62,13 +60,13 @@ public class JdbcVisitRepositoryImpl implements VisitRepository {
}
@Override
public void save(Visit visit) throws DataAccessException {
if (visit.isNew()) {
Number newKey = this.insertVisit.executeAndReturnKey(
createVisitParameterSource(visit));
visit.setId(newKey.intValue());
}
else {
} else {
throw new UnsupportedOperationException("Visit update not supported");
}
}
@ -79,8 +77,7 @@ public class JdbcVisitRepositoryImpl implements VisitRepository {
/**
* Creates a {@link MapSqlParameterSource} based on data values from the
* supplied {@link Visit} instance.
* Creates a {@link MapSqlParameterSource} based on data values from the supplied {@link Visit} instance.
*/
private MapSqlParameterSource createVisitParameterSource(Visit visit) {
return new MapSqlParameterSource()
@ -90,10 +87,12 @@ public class JdbcVisitRepositoryImpl implements VisitRepository {
.addValue("pet_id", visit.getPet().getId());
}
@Override
public List<Visit> findByPetId(Integer petId) {
final List<Visit> visits = this.jdbcTemplate.query(
"SELECT id, visit_date, description FROM visits WHERE pet_id=?",
new ParameterizedRowMapper<Visit>() {
@Override
public Visit mapRow(ResultSet rs, int row) throws SQLException {
Visit visit = new Visit();
visit.setId(rs.getInt("id"));

View file

@ -15,15 +15,14 @@
*/
package org.springframework.samples.petclinic.repository.jpa;
import java.util.Collection;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
/**
* JPA implementation of the {@link OwnerRepository} interface.
@ -41,6 +40,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
private EntityManager em;
@Override
@SuppressWarnings("unchecked")
public Collection<Owner> findByLastName(String lastName) {
// using 'join fetch' because a single query should load both owners and pets
@ -50,6 +50,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
return query.getResultList();
}
@Override
public Owner findById(int id) {
// using 'join fetch' because a single query should load both owners and pets
// using 'left join fetch' because it might happen that an owner does not have pets yet
@ -59,6 +60,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
}
@Override
public void save(Owner owner) {
this.em.merge(owner);

View file

@ -15,16 +15,15 @@
*/
package org.springframework.samples.petclinic.repository.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
/**
* JPA implementation of the {@link PetRepository} interface.
*
@ -40,15 +39,18 @@ public class JpaPetRepositoryImpl implements PetRepository {
@PersistenceContext
private EntityManager em;
@Override
@SuppressWarnings("unchecked")
public List<PetType> findPetTypes() {
return this.em.createQuery("SELECT ptype FROM PetType ptype ORDER BY ptype.name").getResultList();
}
@Override
public Pet findById(int id) {
return this.em.find(Pet.class, id);
}
@Override
public void save(Pet pet) {
this.em.merge(pet);
}

View file

@ -15,18 +15,17 @@
*/
package org.springframework.samples.petclinic.repository.jpa;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.repository.VetRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
/**
* JPA implementation of the {@link VetRepository} interface.
* JPA implementation of the {@link VetRepository} interface.
*
* @author Mike Keith
* @author Rod Johnson
@ -41,7 +40,8 @@ public class JpaVetRepositoryImpl implements VetRepository {
private EntityManager em;
@Cacheable(value="vets")
@Override
@Cacheable(value = "vets")
@SuppressWarnings("unchecked")
public Collection<Vet> findAll() {
return this.em.createQuery("SELECT vet FROM Vet vet join fetch vet.specialties ORDER BY vet.lastName, vet.firstName").getResultList();

View file

@ -15,19 +15,18 @@
*/
package org.springframework.samples.petclinic.repository.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
/**
* JPA implementation of the ClinicService interface using EntityManager.
*
* <p/>
* <p>The mappings are defined in "orm.xml" located in the META-INF directory.
*
* @author Mike Keith
@ -43,11 +42,13 @@ public class JpaVisitRepositoryImpl implements VisitRepository {
private EntityManager em;
@Override
public void save(Visit visit) {
this.em.merge(visit);
}
@Override
@SuppressWarnings("unchecked")
public List<Visit> findByPetId(Integer petId) {
Query query = this.em.createQuery("SELECT visit FROM Visit v where v.pets.id= :id");

View file

@ -15,20 +15,19 @@
*/
package org.springframework.samples.petclinic.repository.springdatajpa;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Collection;
/**
* Using native JPA instead of Spring Data JPA here because of this query:
* "SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName"
* See https://jira.springsource.org/browse/DATAJPA-292 for more details.
* Using native JPA instead of Spring Data JPA here because of this query: "SELECT owner FROM Owner owner left join
* fetch owner.pets WHERE owner.lastName LIKE :lastName" See https://jira.springsource.org/browse/DATAJPA-292 for more
* details.
*
* @author Michael Isvy
*/
@ -39,6 +38,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
private EntityManager em;
@Override
@SuppressWarnings("unchecked")
public Collection<Owner> findByLastName(String lastName) {
// using 'join fetch' because a single query should load both owners and pets
@ -48,6 +48,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
return query.getResultList();
}
@Override
public Owner findById(int id) {
// using 'join fetch' because a single query should load both owners and pets
// using 'left join fetch' because it might happen that an owner does not have pets yet
@ -57,6 +58,7 @@ public class JpaOwnerRepositoryImpl implements OwnerRepository {
}
@Override
public void save(Owner owner) {
this.em.merge(owner);

View file

@ -15,8 +15,6 @@
*/
package org.springframework.samples.petclinic.repository.springdatajpa;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
@ -24,6 +22,8 @@ import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.repository.PetRepository;
import java.util.List;
/**
* Spring Data JPA specialization of the {@link PetRepository} interface
*
@ -32,6 +32,7 @@ import org.springframework.samples.petclinic.repository.PetRepository;
*/
public interface SpringDataPetRepository extends PetRepository, Repository<Pet, Integer> {
@Override
@Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
List<PetType> findPetTypes() throws DataAccessException;
}

View file

@ -15,14 +15,10 @@
*/
package org.springframework.samples.petclinic.service;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.model.*;
import java.util.Collection;
/**

View file

@ -15,15 +15,9 @@
*/
package org.springframework.samples.petclinic.service;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.model.*;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.samples.petclinic.repository.VetRepository;
@ -31,6 +25,8 @@ import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
/**
* Mostly used as a facade for all Petclinic controllers
*
@ -52,56 +48,55 @@ public class ClinicServiceImpl implements ClinicService {
this.visitRepository = visitRepository;
}
@Transactional(readOnly=true)
@Override
@Transactional(readOnly = true)
public Collection<PetType> findPetTypes() throws DataAccessException {
return petRepository.findPetTypes();
}
@Transactional(readOnly=true)
@Override
@Transactional(readOnly = true)
public Owner findOwnerById(int id) throws DataAccessException {
return ownerRepository.findById(id);
}
@Transactional(readOnly=true)
@Override
@Transactional(readOnly = true)
public Collection<Owner> findOwnerByLastName(String lastName) throws DataAccessException {
return ownerRepository.findByLastName(lastName);
}
@Override
@Transactional
public void saveOwner(Owner owner) throws DataAccessException {
ownerRepository.save(owner);
}
@Override
@Transactional
public void saveVisit(Visit visit) throws DataAccessException {
visitRepository.save(visit);
}
@Transactional(readOnly=true)
@Override
@Transactional(readOnly = true)
public Pet findPetById(int id) throws DataAccessException {
return petRepository.findById(id);
}
@Override
@Transactional
public void savePet(Pet pet) throws DataAccessException {
petRepository.save(pet);
}
@Transactional(readOnly=true)
@Override
@Transactional(readOnly = true)
public Collection<Vet> findVets() throws DataAccessException {
return vetRepository.findAll();
}
}

View file

@ -24,8 +24,8 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.StopWatch;
/**
* Simple aspect that monitors call count and call invocation time.
* It uses JMX annotations and therefore can be monitored using any JMX console such as the jConsole
* Simple aspect that monitors call count and call invocation time. It uses JMX annotations and therefore can be
* monitored using any JMX console such as the jConsole
*
* @author Rob Harrop
* @author Juergen Hoeller
@ -78,17 +78,14 @@ public class CallMonitoringAspect {
sw.start("invoke");
try {
return joinPoint.proceed();
}
finally {
} finally {
sw.stop();
synchronized (this) {
this.callCount++;
this.accumulatedCallTime += sw.getTotalTimeMillis();
}
}
}
else {
} else {
return joinPoint.proceed();
}
}

View file

@ -16,32 +16,31 @@
package org.springframework.samples.petclinic.util;
import java.util.Collection;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.samples.petclinic.model.BaseEntity;
import java.util.Collection;
/**
* Utility methods for handling entities. Separate from the BaseEntity class
* mainly because of dependency on the ORM-associated
* ObjectRetrievalFailureException.
* 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
* @since 29.10.2003
* @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.
* 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
* @throws ObjectRetrievalFailureException
* if the entity was not found
*/
public static <T extends BaseEntity> T getById(Collection<T> entities, Class<T> entityClass, int entityId)
throws ObjectRetrievalFailureException {

View file

@ -23,18 +23,18 @@ import org.springframework.web.bind.annotation.RequestMethod;
* Controller used to showcase what happens when an exception is thrown
*
* @author Michael Isvy
*
* Also see how the bean of type 'SimpleMappingExceptionResolver' has been declared inside /WEB-INF/mvc-core-config.xml
* <p/>
* Also see how the bean of type 'SimpleMappingExceptionResolver' has been declared inside
* /WEB-INF/mvc-core-config.xml
*/
@Controller
public class CrashController {
@RequestMapping(value="/oups", method = RequestMethod.GET)
@RequestMapping(value = "/oups", method = RequestMethod.GET)
public String triggerException() {
throw new RuntimeException("Expected: controller used to showcase what " +
"happens when an exception is thrown");
}
}

View file

@ -15,10 +15,6 @@
*/
package org.springframework.samples.petclinic.web;
import java.util.Collection;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.service.ClinicService;
@ -26,16 +22,14 @@ 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.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.Collection;
/**
*
* @author Juergen Hoeller
* @author Ken Krebs
* @author Arjen Poutsma
@ -58,19 +52,18 @@ public class OwnerController {
dataBinder.setDisallowedFields("id");
}
@RequestMapping(value="/owners/new", method = RequestMethod.GET)
@RequestMapping(value = "/owners/new", method = RequestMethod.GET)
public String initCreationForm(Model model) {
Owner owner = new Owner();
model.addAttribute(owner);
return "owners/createOrUpdateOwnerForm";
}
@RequestMapping(value="/owners/new", method = RequestMethod.POST)
@RequestMapping(value = "/owners/new", method = RequestMethod.POST)
public String processCreationForm(@Valid Owner owner, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "owners/createOrUpdateOwnerForm";
}
else {
} else {
this.clinicService.saveOwner(owner);
status.setComplete();
return "redirect:/owners/" + owner.getId();
@ -102,27 +95,25 @@ public class OwnerController {
// multiple owners found
model.addAttribute("selections", results);
return "owners/ownersList";
}
else {
} else {
// 1 owner found
owner = results.iterator().next();
return "redirect:/owners/" + owner.getId();
}
}
@RequestMapping(value="/owners/{ownerId}/edit", method = RequestMethod.GET)
@RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.GET)
public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
Owner owner = this.clinicService.findOwnerById(ownerId);
model.addAttribute(owner);
return "owners/createOrUpdateOwnerForm";
}
@RequestMapping(value="/owners/{ownerId}/edit", method = RequestMethod.PUT)
@RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.PUT)
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "owners/createOrUpdateOwnerForm";
}
else {
} else {
this.clinicService.saveOwner(owner);
status.setComplete();
return "redirect:/owners/{ownerId}";

View file

@ -15,8 +15,6 @@
*/
package org.springframework.samples.petclinic.web;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
@ -26,16 +24,12 @@ 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.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import java.util.Collection;
/**
*
* @author Juergen Hoeller
* @author Ken Krebs
* @author Arjen Poutsma
@ -62,7 +56,7 @@ public class PetController {
dataBinder.setDisallowedFields("id");
}
@RequestMapping(value="/owners/{ownerId}/pets/new", method = RequestMethod.GET)
@RequestMapping(value = "/owners/{ownerId}/pets/new", method = RequestMethod.GET)
public String initCreationForm(@PathVariable("ownerId") int ownerId, Model model) {
Owner owner = this.clinicService.findOwnerById(ownerId);
Pet pet = new Pet();
@ -71,34 +65,32 @@ public class PetController {
return "pets/createOrUpdatePetForm";
}
@RequestMapping(value="/owners/{ownerId}/pets/new", method = RequestMethod.POST)
@RequestMapping(value = "/owners/{ownerId}/pets/new", method = RequestMethod.POST)
public String processCreationForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "pets/createOrUpdatePetForm";
}
else {
} else {
this.clinicService.savePet(pet);
status.setComplete();
return "redirect:/owners/{ownerId}";
}
}
@RequestMapping(value="/owners/*/pets/{petId}/edit", method = RequestMethod.GET)
@RequestMapping(value = "/owners/*/pets/{petId}/edit", method = RequestMethod.GET)
public String initUpdateForm(@PathVariable("petId") int petId, Model model) {
Pet pet = this.clinicService.findPetById(petId);
model.addAttribute("pet", pet);
return "pets/createOrUpdatePetForm";
}
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = { RequestMethod.PUT, RequestMethod.POST })
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}/edit", method = {RequestMethod.PUT, RequestMethod.POST})
public String processUpdateForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
// we're not using @Valid annotation here because it is easier to define such validation rule in Java
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "pets/createOrUpdatePetForm";
}
else {
} else {
this.clinicService.savePet(pet);
status.setComplete();
return "redirect:/owners/{ownerId}";

View file

@ -16,22 +16,21 @@
package org.springframework.samples.petclinic.web;
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.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.service.ClinicService;
import java.text.ParseException;
import java.util.Collection;
import java.util.Locale;
/**
* 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: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI
* 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: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI
* - A nice blog entry from Gordon Dickens: http://gordondickens.com/wordpress/2010/09/30/using-spring-3-0-custom-type-converter/
*
* <p/>
* Also see how the bean 'conversionService' has been declared inside /WEB-INF/mvc-core-config.xml
*
* @author Mark Fisher
@ -61,7 +60,7 @@ public class PetTypeFormatter implements Formatter<PetType> {
return type;
}
}
throw new ParseException("type not found: "+text, 0);
throw new ParseException("type not found: " + text, 0);
}
}

View file

@ -31,8 +31,7 @@ public class PetValidator {
String name = pet.getName();
if (!StringUtils.hasLength(name)) {
errors.rejectValue("name", "required", "required");
}
else if (pet.isNew() && pet.getOwner().getPet(name, true) != null) {
} else if (pet.isNew() && pet.getOwner().getPet(name, true) != null) {
errors.rejectValue("name", "duplicate", "already exists");
}
}

View file

@ -23,7 +23,6 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author Juergen Hoeller
* @author Mark Fisher
* @author Ken Krebs
@ -51,7 +50,4 @@ public class VetController {
}
}

View file

@ -15,20 +15,18 @@
*/
package org.springframework.samples.petclinic.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.syndication.feed.atom.Content;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.model.Vets;
import org.springframework.web.servlet.view.feed.AbstractAtomFeedView;
import com.sun.syndication.feed.atom.Content;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A view creating a Atom representation from a list of Visit objects.

View file

@ -15,8 +15,6 @@
*/
package org.springframework.samples.petclinic.web;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.Visit;
@ -25,16 +23,13 @@ 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.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
/**
*
* @author Juergen Hoeller
* @author Ken Krebs
* @author Arjen Poutsma
@ -57,7 +52,7 @@ public class VisitController {
dataBinder.setDisallowedFields("id");
}
@RequestMapping(value="/owners/*/pets/{petId}/visits/new", method = RequestMethod.GET)
@RequestMapping(value = "/owners/*/pets/{petId}/visits/new", method = RequestMethod.GET)
public String initNewVisitForm(@PathVariable("petId") int petId, Model model) {
Pet pet = this.clinicService.findPetById(petId);
Visit visit = new Visit();
@ -66,19 +61,18 @@ public class VisitController {
return "pets/createOrUpdateVisitForm";
}
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST)
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST)
public String processNewVisitForm(@Valid Visit visit, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "pets/createOrUpdateVisitForm";
}
else {
} else {
this.clinicService.saveVisit(visit);
status.setComplete();
return "redirect:/owners/{ownerId}";
}
}
@RequestMapping(value="/owners/*/pets/{petId}/visits", method=RequestMethod.GET)
@RequestMapping(value = "/owners/*/pets/{petId}/visits", method = RequestMethod.GET)
public ModelAndView showVisits(@PathVariable int petId) {
ModelAndView mav = new ModelAndView("visitList");
mav.addObject("visits", this.clinicService.findPetById(petId).getVisits());

View file

@ -1,7 +1,7 @@
<html>
<body>
<p>
The Spring Data Binding framework, an internal library used by Spring Web Flow.
The Spring Data Binding framework, an internal library used by Spring Web Flow.
</p>
</body>
</html>

View file

@ -1,10 +1,10 @@
drop table vet_specialties if exists;
drop table vets if exists;
drop table specialties if exists;
drop table visits if exists;
drop table pets if exists;
drop table types if exists;
drop table owners if exists;
DROP TABLE vet_specialties IF EXISTS;
DROP TABLE vets IF EXISTS;
DROP TABLE specialties IF EXISTS;
DROP TABLE visits IF EXISTS;
DROP TABLE pets IF EXISTS;
DROP TABLE types IF EXISTS;
DROP TABLE owners IF EXISTS;
CREATE TABLE vets (
@ -12,26 +12,26 @@ CREATE TABLE vets (
first_name VARCHAR(30),
last_name VARCHAR(30)
);
CREATE INDEX vets_last_name ON vets(last_name);
CREATE INDEX vets_last_name ON vets (last_name);
CREATE TABLE specialties (
id INTEGER IDENTITY PRIMARY KEY,
name VARCHAR(80)
);
CREATE INDEX specialties_name ON specialties(name);
CREATE INDEX specialties_name ON specialties (name);
CREATE TABLE vet_specialties (
vet_id INTEGER NOT NULL,
specialty_id INTEGER NOT NULL
);
alter table vet_specialties add constraint fk_vet_specialties_vets foreign key (vet_id) references vets(id);
alter table vet_specialties add constraint fk_vet_specialties_specialties foreign key (specialty_id) references specialties(id);
ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_vets FOREIGN KEY (vet_id) REFERENCES vets (id);
ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_specialties FOREIGN KEY (specialty_id) REFERENCES specialties (id);
CREATE TABLE types (
id INTEGER IDENTITY PRIMARY KEY,
name VARCHAR(80)
);
CREATE INDEX types_name ON types(name);
CREATE INDEX types_name ON types (name);
CREATE TABLE owners (
id INTEGER IDENTITY PRIMARY KEY,
@ -41,7 +41,7 @@ CREATE TABLE owners (
city VARCHAR(80),
telephone VARCHAR(20)
);
CREATE INDEX owners_last_name ON owners(last_name);
CREATE INDEX owners_last_name ON owners (last_name);
CREATE TABLE pets (
id INTEGER IDENTITY PRIMARY KEY,
@ -50,9 +50,9 @@ CREATE TABLE pets (
type_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL
);
alter table pets add constraint fk_pets_owners foreign key (owner_id) references owners(id);
alter table pets add constraint fk_pets_types foreign key (type_id) references types(id);
CREATE INDEX pets_name ON pets(name);
ALTER TABLE pets ADD CONSTRAINT fk_pets_owners FOREIGN KEY (owner_id) REFERENCES owners (id);
ALTER TABLE pets ADD CONSTRAINT fk_pets_types FOREIGN KEY (type_id) REFERENCES types (id);
CREATE INDEX pets_name ON pets (name);
CREATE TABLE visits (
id INTEGER IDENTITY PRIMARY KEY,
@ -60,5 +60,5 @@ CREATE TABLE visits (
visit_date DATE,
description VARCHAR(255)
);
alter table visits add constraint fk_visits_pets foreign key (pet_id) references pets(id);
CREATE INDEX visits_pet_id ON visits(pet_id);
ALTER TABLE visits ADD CONSTRAINT fk_visits_pets FOREIGN KEY (pet_id) REFERENCES pets (id);
CREATE INDEX visits_pet_id ON visits (pet_id);

View file

@ -12,6 +12,6 @@
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LRU" />
memoryStoreEvictionPolicy="LRU"/>
</ehcache>

View file

@ -371,7 +371,8 @@
<xs:element name="sizeOfPolicy">
<xs:complexType>
<xs:attribute name="maxDepth" use="required" type="xs:integer"/>
<xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue" type="maxDepthExceededBehavior"/>
<xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue"
type="maxDepthExceededBehavior"/>
</xs:complexType>
</xs:element>

View file

@ -1,166 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Authors: Chris Taylor, Ceki Gulcu. -->
<!-- Version: 1.2 -->
<!-- A configuration element consists of optional renderer
elements,appender elements, categories and an optional root
element. -->
<!ELEMENT log4j:configuration (renderer*, appender*,(category|logger)*,root?,
categoryFactory?)>
<!-- The "threshold" attribute takes a level value such that all -->
<!-- logging statements with a level equal or below this value are -->
<!-- disabled. -->
<!-- Setting the "debug" enable the printing of internal log4j logging -->
<!-- statements. -->
<!-- By default, debug attribute is "null", meaning that we not do touch -->
<!-- internal log4j logging settings. The "null" value for the threshold -->
<!-- attribute can be misleading. The threshold field of a repository -->
<!-- cannot be set to null. The "null" value for the threshold attribute -->
<!-- simply means don't touch the threshold field, the threshold field -->
<!-- keeps its old value. -->
<!ATTLIST log4j:configuration
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
threshold (all|debug|info|warn|error|fatal|off|null) "null"
debug (true|false|null) "null"
>
<!-- renderer elements allow the user to customize the conversion of -->
<!-- message objects to String. -->
<!ELEMENT renderer EMPTY>
<!ATTLIST renderer
renderedClass CDATA #REQUIRED
renderingClass CDATA #REQUIRED
>
<!-- Appenders must have a name and a class. -->
<!-- Appenders may contain an error handler, a layout, optional parameters -->
<!-- and filters. They may also reference (or include) other appenders. -->
<!ELEMENT appender (errorHandler?, param*, layout?, filter*, appender-ref*)>
<!ATTLIST appender
name ID #REQUIRED
class CDATA #REQUIRED
>
<!ELEMENT layout (param*)>
<!ATTLIST layout
class CDATA #REQUIRED
>
<!ELEMENT filter (param*)>
<!ATTLIST filter
class CDATA #REQUIRED
>
<!-- ErrorHandlers can be of any class. They can admit any number of -->
<!-- parameters. -->
<!ELEMENT errorHandler (param*, root-ref?, logger-ref*, appender-ref?)>
<!ATTLIST errorHandler
class CDATA #REQUIRED
>
<!ELEMENT root-ref EMPTY>
<!ELEMENT logger-ref EMPTY>
<!ATTLIST logger-ref
ref IDREF #REQUIRED
>
<!ELEMENT param EMPTY>
<!ATTLIST param
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!-- The priority class is org.apache.log4j.Level by default -->
<!ELEMENT priority (param*)>
<!ATTLIST priority
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- The level class is org.apache.log4j.Level by default -->
<!ELEMENT level (param*)>
<!ATTLIST level
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named category. -->
<!ELEMENT category (param*,(priority|level)?,appender-ref*)>
<!ATTLIST category
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named logger. -->
<!ELEMENT logger (level?,appender-ref*)>
<!ATTLIST logger
name ID #REQUIRED
additivity (true|false) "true"
>
<!ELEMENT categoryFactory (param*)>
<!ATTLIST categoryFactory
class CDATA #REQUIRED>
<!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
ref IDREF #REQUIRED
>
<!-- If no priority element is specified, then the configurator MUST not -->
<!-- touch the priority of root. -->
<!-- The root category always exists and cannot be subclassed. -->
<!ELEMENT root (param*, (priority|level)?, appender-ref*)>
<!-- ==================================================================== -->
<!-- A logging event -->
<!-- ==================================================================== -->
<!ELEMENT log4j:eventSet (log4j:event*)>
<!ATTLIST log4j:eventSet
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
version (1.1|1.2) "1.2"
includesLocationInfo (true|false) "true"
>
<!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?,
log4j:locationInfo?) >
<!-- The timestamp format is application dependent. -->
<!ATTLIST log4j:event
logger CDATA #REQUIRED
level CDATA #REQUIRED
thread CDATA #REQUIRED
timestamp CDATA #REQUIRED
>
<!ELEMENT log4j:message (#PCDATA)>
<!ELEMENT log4j:NDC (#PCDATA)>
<!ELEMENT log4j:throwable (#PCDATA)>
<!ELEMENT log4j:locationInfo EMPTY>
<!ATTLIST log4j:locationInfo
class CDATA #REQUIRED
method CDATA #REQUIRED
file CDATA #REQUIRED
line CDATA #REQUIRED
>

View file

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %c - %m%n" />
</layout>
</appender>
<logger name="org.springframework.test.web">
<level value="trace" />
</logger>
<!-- Root Logger -->
<root>
<priority value="info" /><!--
<level value="info"></level>
--><appender-ref ref="console" />
</root>
</log4j:configuration>

View file

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.samples.petclinic" level="debug"/>
<root level="warn">
<appender-ref ref="console"/>
</root>
</configuration>

View file

@ -2,13 +2,20 @@
<!--
Application context definition for PetClinic on JPA.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- ========================= RESOURCE DEFINITIONS ========================= -->
@ -44,10 +51,11 @@
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
p:database="${jpa.database}" p:showSql="${jpa.showSql}"/>
</property>
<property name="persistenceUnitName" value="petclinic" />
<property name="packagesToScan" value="org/springframework/samples/petclinic" />
<!-- gDickens: BOTH Persistence Unit and Packages to Scan are NOT compatible, persistenceUnit will win -->
<property name="persistenceUnitName" value="petclinic"/>
<property name="packagesToScan" value="org.springframework.samples.petclinic"/>
</bean>
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
@ -55,7 +63,6 @@
p:entityManagerFactory-ref="entityManagerFactory"/>
<!--
Post-processor to perform exception translation on @Repository classes (from native
exceptions such as JPA PersistenceExceptions to Spring's DataAccessException hierarchy).
@ -70,15 +77,15 @@
p:dataSource-ref="dataSource"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
<constructor-arg ref="dataSource"/>
</bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<context:component-scan base-package="org.springframework.samples.petclinic.repository.jdbc"/>
</beans>
<beans profile="jpa">
@ -88,14 +95,13 @@
PersistenceExceptions will be auto-translated due to @Repository.
-->
<context:component-scan base-package="org.springframework.samples.petclinic.repository.jpa"/>
</beans>
<beans profile="spring-data-jpa">
<jpa:repositories base-package="org.springframework.samples.petclinic.repository.springdatajpa"/>
<!-- Custom configuration for the custom implementation based on JPA -->
<bean id="owerRepository" class="org.springframework.samples.petclinic.repository.springdatajpa.JpaOwnerRepositoryImpl"/>
<bean id="owerRepository"
class="org.springframework.samples.petclinic.repository.springdatajpa.JpaOwnerRepositoryImpl"/>
</beans>
</beans>

View file

@ -6,10 +6,12 @@
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!-- ========================= DATASOURCE DEFINITION ========================= -->

View file

@ -4,9 +4,6 @@
# various application context XML files (e.g., "applicationContext-*.xml").
# Targeted at system administrators, to avoid touching the context XML files.
#-------------------------------------------------------------------------------
# HSQL Settings

View file

@ -2,22 +2,27 @@
<!--
- DispatcherServlet application context for PetClinic's web tier.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="mvc-view-config.xml"/>
<!--
- POJOs labeled with the @Controller and @Service annotations are auto-detected.
-->
<context:component-scan base-package="org.springframework.samples.petclinic.web, org.springframework.samples.petclinic.service"/>
<context:component-scan
base-package="org.springframework.samples.petclinic.web, org.springframework.samples.petclinic.service"/>
<mvc:annotation-driven conversion-service="conversionService" />
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- all resources inside folder src/main/webapp/resources are mapped so they can be refered to inside JSP files
(see header.jsp for more details) -->
@ -28,11 +33,10 @@
<mvc:view-controller path="/" view-name="welcome"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="org.springframework.samples.petclinic.web.PetTypeFormatter" />
<bean class="org.springframework.samples.petclinic.web.PetTypeFormatter"/>
</set>
</property>
</bean>
@ -50,8 +54,10 @@
-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- view name resolved using bean of type InternalResourceViewResolver (declared in mvc-view-config.xml) -->
<property name="defaultErrorView" value="exception"/> <!-- results into 'WEB-INF/jsp/exception.jsp' -->
<property name="warnLogCategory" value="warn"/> <!-- needed otherwise exceptions won't be logged anywhere -->
<property name="defaultErrorView" value="exception"/>
<!-- results into 'WEB-INF/jsp/exception.jsp' -->
<property name="warnLogCategory" value="warn"/>
<!-- needed otherwise exceptions won't be logged anywhere -->
</bean>
</beans>

View file

@ -2,15 +2,13 @@
<!--
- DispatcherServlet application context for PetClinic's web tier.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
- The ContentNegotiatingViewResolver delegates to the InternalResourceViewResolver and BeanNameViewResolver,
- and uses the requested media type (determined by the path extension) to pick a matching view.
@ -30,12 +28,12 @@
<!-- Default viewClass: JSTL view (JSP with html output) -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'vets' is mapped to '/WEB-INF/jsp/vets.jsp' -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Used here for 'xml' and 'atom' views -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!-- Renders an Atom feed of the visits. Used by the BeanNameViewResolver -->
<bean id="vets/vetList.atom" class="org.springframework.samples.petclinic.web.VetsAtomView"/>

View file

@ -2,13 +2,19 @@
<!--
Application context definition for PetClinic on JPA.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--
Simply defining this bean will cause requests to owner names to be saved.
@ -26,10 +32,10 @@
Exporter that exposes the CallMonitoringAspect via JMX,
based on the @ManagedResource, @ManagedAttribute, and @ManagedOperation annotations.
-->
<context:mbean-export />
<context:mbean-export/>
<!-- enables scanning for @Cacheable annotation -->
<cache:annotation-driven />
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
@ -40,6 +46,4 @@
</bean>
</beans>

View file

@ -1,15 +1,17 @@
<html lang="en">
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="fragments/bodyHeader.jsp"/>
<spring:url value="/resources/images/pets.png" var="petsImage"/>
<img src="${petsImage}" />
<img src="${petsImage}"/>
<h2>Something happened...</h2>
<p>${exception.message}</p>
<!-- Exception: ${exception.message}.
@ -21,7 +23,7 @@
<jsp:include page="fragments/footer.jsp"/>
</div>
</div>
</body>
</html>

View file

@ -2,15 +2,22 @@
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<spring:url value="/resources/images/banner-graphic.png" var="banner"/>
<img src="${banner}" />
<img src="${banner}"/>
<div class="navbar" style="width: 601px;">
<div class="navbar-inner">
<ul class="nav">
<li style="width: 100px;"><a href="<spring:url value="/" htmlEscape="true" />"><i class="icon-home"></i> Home</a></li>
<li style="width: 130px;"><a href="<spring:url value="/owners/find.html" htmlEscape="true" />"><i class="icon-search"></i> Find owners</a></li>
<li style="width: 140px;"><a href="<spring:url value="/vets.html" htmlEscape="true" />"><i class="icon-th-list"></i> Veterinarians</a></li>
<li style="width: 90px;"><a href="<spring:url value="/oups.html" htmlEscape="true" />" title="trigger a RuntimeException to see how it is handled"><i class="icon-warning-sign"></i> Error</a></li>
<li style="width: 80px;"><a href="#" title="not available yet. Work in progress!!"><i class=" icon-question-sign"></i> Help</a></li>
<li style="width: 100px;"><a href="<spring:url value="/" htmlEscape="true" />"><i class="icon-home"></i>
Home</a></li>
<li style="width: 130px;"><a href="<spring:url value="/owners/find.html" htmlEscape="true" />"><i
class="icon-search"></i> Find owners</a></li>
<li style="width: 140px;"><a href="<spring:url value="/vets.html" htmlEscape="true" />"><i
class="icon-th-list"></i> Veterinarians</a></li>
<li style="width: 90px;"><a href="<spring:url value="/oups.html" htmlEscape="true" />"
title="trigger a RuntimeException to see how it is handled"><i
class="icon-warning-sign"></i> Error</a></li>
<li style="width: 80px;"><a href="#" title="not available yet. Work in progress!!"><i
class=" icon-question-sign"></i> Help</a></li>
</ul>
</div>
</div>

View file

@ -1,10 +1,11 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<table class="footer">
<table class="footer">
<tr>
<td></td>
<td align="right"><img src="<spring:url value="/resources/images/springsource-logo.png" htmlEscape="true" />" alt="Sponsored by SpringSource"/></td>
<td align="right"><img src="<spring:url value="/resources/images/springsource-logo.png" htmlEscape="true" />"
alt="Sponsored by SpringSource"/></td>
</tr>
</table>
</table>

View file

@ -1,7 +1,7 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!--
PetClinic :: a Spring Framework demonstration
PetClinic :: a Spring Framework demonstration
-->
<head>
@ -9,19 +9,19 @@
<title>PetClinic :: a Spring Framework demonstration</title>
<spring:url value="/webjars/bootstrap/2.2.1/css/bootstrap.min.css" var="bootstrapCss" />
<spring:url value="/webjars/bootstrap/2.2.1/css/bootstrap.min.css" var="bootstrapCss"/>
<link href="${bootstrapCss}" rel="stylesheet"/>
<spring:url value="/resources/css/petclinic.css" var="petclinicCss" />
<spring:url value="/resources/css/petclinic.css" var="petclinicCss"/>
<link href="${petclinicCss}" rel="stylesheet"/>
<spring:url value="/webjars/jquery/1.8.2/jquery.js" var="jQuery" />
<spring:url value="/webjars/jquery/1.8.2/jquery.js" var="jQuery"/>
<script src="${jQuery}"></script>
<spring:url value="/webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js" var="jQueryUi" />
<spring:url value="/webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js" var="jQueryUi"/>
<script src="${jQueryUi}"></script>
<spring:url value="/webjars/jquery-ui/1.9.1/css/smoothness/jquery-ui-1.9.1.custom.css" var="jQueryUiCss" />
<spring:url value="/webjars/jquery-ui/1.9.1/css/smoothness/jquery-ui-1.9.1.custom.css" var="jQueryUiCss"/>
<link href="${jQueryUiCss}" rel="stylesheet"></link>
</head>

View file

@ -11,7 +11,7 @@
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<c:choose>
<c:when test="${owner['new']}"><c:set var="method" value="post"/></c:when>
@ -22,11 +22,11 @@
<c:if test="${owner['new']}">New </c:if> Owner
</h2>
<form:form modelAttribute="owner" method="${method}" class="form-horizontal" id="add-owner-form">
<petclinic:inputField label="First Name" name="firstName" />
<petclinic:inputField label="Last Name" name="lastName" />
<petclinic:inputField label="Address" name="address" />
<petclinic:inputField label="City" name="city" />
<petclinic:inputField label="Telephone" name="telephone" />
<petclinic:inputField label="First Name" name="firstName"/>
<petclinic:inputField label="Last Name" name="lastName"/>
<petclinic:inputField label="Address" name="address"/>
<petclinic:inputField label="City" name="city"/>
<petclinic:inputField label="Telephone" name="telephone"/>
<div class="form-actions">
<c:choose>
@ -39,8 +39,8 @@
</c:choose>
</div>
</form:form>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
</html>

View file

@ -8,18 +8,19 @@
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<h2>Find Owners</h2>
<spring:url value="/owners.html" var="formUrl"/>
<form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get" class="form-horizontal" id="search-owner-form">
<form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get" class="form-horizontal"
id="search-owner-form">
<fieldset>
<div class="control-group" id="lastName">
<label class="control-label">Last name </label>
<form:input path="lastName" size="30" maxlength="80"/>
<span class="help-inline"><form:errors path="*" /></span>
<span class="help-inline"><form:errors path="*"/></span>
</div>
<div class="form-actions">
<button type="submit">Find Owner</button>
@ -32,7 +33,7 @@
<jsp:include page="../fragments/footer.jsp"/>
</div>
</div>
</body>
</html>

View file

@ -9,7 +9,7 @@
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<h2>Owner Information</h2>
@ -28,7 +28,7 @@
<td><c:out value="${owner.city}"/></td>
</tr>
<tr>
<th>Telephone </th>
<th>Telephone</th>
<td><c:out value="${owner.telephone}"/></td>
</tr>
</table>
@ -36,13 +36,13 @@
<tr>
<td colspan="2" align="center">
<spring:url value="{ownerId}/edit.html" var="editUrl">
<spring:param name="ownerId" value="${owner.id}" />
<spring:param name="ownerId" value="${owner.id}"/>
</spring:url>
<a href="${fn:escapeXml(editUrl)}">Edit Owner</a>
</td>
<td>
<spring:url value="{ownerId}/pets/new.html" var="addUrl">
<spring:param name="ownerId" value="${owner.id}" />
<spring:param name="ownerId" value="${owner.id}"/>
</spring:url>
<a href="${fn:escapeXml(addUrl)}">Add New Pet</a>
</td>
@ -59,7 +59,7 @@
<dt>Name</dt>
<dd><c:out value="${pet.name}"/></dd>
<dt>Birth Date</dt>
<dd><joda:format value="${pet.birthDate}" pattern="yyyy-MM-dd" /></dd>
<dd><joda:format value="${pet.birthDate}" pattern="yyyy-MM-dd"/></dd>
<dt>Type</dt>
<dd><c:out value="${pet.type.name}"/></dd>
</dl>
@ -113,7 +113,7 @@
<jsp:include page="../fragments/footer.jsp"/>
</div>
</div>
</body>

View file

@ -9,7 +9,7 @@
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<h2>Owners</h2>
@ -29,7 +29,7 @@
<spring:url value="owners/{ownerId}.html" var="ownerUrl">
<spring:param name="ownerId" value="${owner.id}"/>
</spring:url>
<a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}" /></a>
<a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}"/></a>
</td>
<td><c:out value="${owner.address}"/></td>
<td><c:out value="${owner.city}"/></td>
@ -44,7 +44,7 @@
</table>
<jsp:include page="../fragments/footer.jsp"/>
</div>
</div>
</body>
</html>

View file

@ -1,6 +1,6 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="petclinic" tagdir="/WEB-INF/tags" %>
@ -10,18 +10,18 @@
<body>
<script>
$(function() {
$(function () {
$("#birthDate").datepicker({ dateFormat: 'yy/mm/dd'});
});
</script>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp" />
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<c:choose>
<c:when test="${pet['new']}">
<c:set var="method" value="post" />
<c:set var="method" value="post"/>
</c:when>
<c:otherwise>
<c:set var="method" value="put" />
<c:set var="method" value="put"/>
</c:otherwise>
</c:choose>
@ -37,8 +37,8 @@
<c:out value="${pet.owner.firstName} ${pet.owner.lastName}"/>
</div>
<petclinic:inputField label="Name" name="name" />
<petclinic:inputField label="Birth Date" name="birthDate" />
<petclinic:inputField label="Name" name="name"/>
<petclinic:inputField label="Birth Date" name="birthDate"/>
<div class="control-group">
<label class="control-label">Type </label>
<form:select path="type" items="${types}" size="5"/>
@ -56,8 +56,8 @@
</form:form>
<c:if test="${!pet['new']}">
</c:if>
<jsp:include page="../fragments/footer.jsp" />
</div>
<jsp:include page="../fragments/footer.jsp"/>
</div>
</body>
</html>

View file

@ -10,12 +10,12 @@
<body>
<script>
$(function() {
<script>
$(function () {
$("#date").datepicker({ dateFormat: 'yy/mm/dd'});
});
</script>
<div class="container">
</script>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<h2><c:if test="${visit['new']}">New </c:if>Visit</h2>
@ -30,26 +30,28 @@
</tr>
</thead>
<tr>
<td><c:out value="${visit.pet.name}" /></td>
<td><c:out value="${visit.pet.name}"/></td>
<td><joda:format value="${visit.pet.birthDate}" pattern="yyyy/MM/dd"/></td>
<td><c:out value="${visit.pet.type.name}" /></td>
<td><c:out value="${visit.pet.owner.firstName} ${visit.pet.owner.lastName}" /></td>
<td><c:out value="${visit.pet.type.name}"/></td>
<td><c:out value="${visit.pet.owner.firstName} ${visit.pet.owner.lastName}"/></td>
</tr>
</table>
<form:form modelAttribute="visit">
<div class="control-group">
<label class="control-label">Date </label>
<div class="controls">
<form:input path="date" />
<span class="help-inline"><form:errors path="date" /></span>
<form:input path="date"/>
<span class="help-inline"><form:errors path="date"/></span>
</div>
</div>
<div class="control-group">
<label class="control-label">Description </label>
<div class="controls">
<form:input path="description" />
<span class="help-inline"><form:errors path="description" /></span>
<form:input path="description"/>
<span class="help-inline"><form:errors path="description"/></span>
</div>
</div>
<div class="form-actions">
@ -69,14 +71,14 @@
<c:if test="${!visit['new']}">
<tr>
<td><joda:format value="${visit.date}" pattern="yyyy/MM/dd"/></td>
<td><c:out value="${visit.description}" /></td>
<td><c:out value="${visit.description}"/></td>
</tr>
</c:if>
</c:forEach>
</table>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
</html>

View file

@ -9,7 +9,7 @@
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<h2>Veterinarians</h2>
@ -24,10 +24,10 @@
<tbody>
<c:forEach var="vet" items="${vets.vetList}">
<tr>
<td><c:out value="${vet.firstName} ${vet.lastName}" /></td>
<td><c:out value="${vet.firstName} ${vet.lastName}"/></td>
<td>
<c:forEach var="specialty" items="${vet.specialties}">
<c:out value="${specialty.name}" />
<c:out value="${specialty.name}"/>
</c:forEach>
<c:if test="${vet.nrOfSpecialties == 0}">none</c:if>
</td>
@ -47,7 +47,7 @@
</table>
<jsp:include page="../fragments/footer.jsp"/>
</div>
</body>
</div>
</body>
</html>

View file

@ -7,15 +7,15 @@
<jsp:include page="fragments/headTag.jsp"/>
<body>
<div class="container">
<div class="container">
<jsp:include page="fragments/bodyHeader.jsp"/>
<h2><fmt:message key="welcome"/></h2>
<spring:url value="/resources/images/pets.png" htmlEscape="true" var="petsImage"/>
<img src="${petsImage}" />
<img src="${petsImage}"/>
<jsp:include page="fragments/footer.jsp"/>
</div>
</div>
</body>
</html>

View file

@ -1,13 +1,16 @@
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ attribute name="name" required="true" rtexprvalue="true" description="Name of corresponding property in bean object"%>
<%@ attribute name="label" required="true" rtexprvalue="true" description="Label appears in red color if input is considered as invalid after submission"%>
<%@ attribute name="name" required="true" rtexprvalue="true"
description="Name of corresponding property in bean object" %>
<%@ attribute name="label" required="true" rtexprvalue="true"
description="Label appears in red color if input is considered as invalid after submission" %>
<spring:bind path="${name}">
<c:set var="cssGroup" value="control-group ${status.error ? 'error' : '' }"/>
<div class="${cssGroup}">
<label class="control-label">${label}</label>
<div class="controls">
<form:input path="${name}"/>
<span class="help-inline">${status.errorMessage}</span>

View file

@ -1,8 +1,9 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring PetClinic</display-name>
<description>Spring PetClinic sample application</description>

View file

@ -16,6 +16,6 @@ input[type="text"] {
color: #000000;
}
.form-horizontal .control-label {
.form-horizontal .control-label {
text-align: left;
}

View file

@ -15,14 +15,12 @@
*/
package org.springframework.samples.petclinic.model;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.transaction.annotation.Transactional;
/**
* JUnit test for the {@link Owner} class.
*
@ -30,7 +28,8 @@ import org.springframework.transaction.annotation.Transactional;
*/
public class OwnerTests {
@Test @Transactional
@Test
@Transactional
public void testHasPet() {
Owner owner = new Owner();
Pet fido = new Pet();

View file

@ -15,44 +15,29 @@
*/
package org.springframework.samples.petclinic.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <p>
* Base class for {@link OwnerRepository} integration tests.
* </p>
* <p>
* Subclasses should specify Spring context configuration using {@link ContextConfiguration @ContextConfiguration} annotation
* </p>
* <p>
* AbstractOwnerRepositoryTests and its subclasses benefit from the following services
* provided by the Spring TestContext Framework:
* </p>
* <ul>
* <li><strong>Spring IoC container caching</strong> which spares us
* unnecessary set up time between test execution.</li>
* <li><strong>Dependency Injection</strong> of test fixture instances,
* meaning that we don't need to perform application context lookups. See the
* use of {@link Autowired @Autowired} on the <code>{@link AbstractOwnerRepositoryTests#ownerRepository ownerRepository}</code> instance
* variable, which uses autowiring <em>by type</em>.
* <li><strong>Transaction management</strong>, 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.
* <li> An {@link org.springframework.context.ApplicationContext ApplicationContext} is
* also inherited and can be used for explicit bean lookup if necessary.
* </li>
* </ul>
* <p> Base class for {@link OwnerRepository} integration tests. </p> <p> Subclasses should specify Spring context
* configuration using {@link ContextConfiguration @ContextConfiguration} annotation </p> <p>
* AbstractOwnerRepositoryTests and its subclasses benefit from the following services provided by the Spring
* TestContext Framework: </p> <ul> <li><strong>Spring IoC container caching</strong> which spares us unnecessary set up
* time between test execution.</li> <li><strong>Dependency Injection</strong> of test fixture instances, meaning that
* we don't need to perform application context lookups. See the use of {@link Autowired @Autowired} on the <code>{@link
* AbstractOwnerRepositoryTests#ownerRepository ownerRepository}</code> instance variable, which uses autowiring <em>by
* type</em>. <li><strong>Transaction management</strong>, 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. <li> An {@link org.springframework.context.ApplicationContext
* ApplicationContext} is also inherited and can be used for explicit bean lookup if necessary. </li> </ul>
*
* @author Ken Krebs
* @author Rod Johnson
@ -65,7 +50,8 @@ public abstract class AbstractOwnerRepositoryTests {
@Autowired
protected OwnerRepository ownerRepository;
@Test @Transactional
@Test
@Transactional
public void findOwners() {
Collection<Owner> owners = this.ownerRepository.findByLastName("Davis");
assertEquals(2, owners.size());
@ -73,7 +59,8 @@ public abstract class AbstractOwnerRepositoryTests {
assertEquals(0, owners.size());
}
@Test @Transactional
@Test
@Transactional
public void findSingleOwner() {
Owner owner1 = this.ownerRepository.findById(1);
assertTrue(owner1.getLastName().startsWith("Franklin"));
@ -83,7 +70,8 @@ public abstract class AbstractOwnerRepositoryTests {
assertEquals(owner1.getPets().size(), 1);
}
@Test @Transactional
@Test
@Transactional
public void insertOwner() {
Collection<Owner> owners = this.ownerRepository.findByLastName("Schultz");
int found = owners.size();
@ -98,7 +86,8 @@ public abstract class AbstractOwnerRepositoryTests {
assertEquals("Verifying number of owners after inserting a new one.", found + 1, owners.size());
}
@Test @Transactional
@Test
@Transactional
public void updateOwner() throws Exception {
Owner o1 = this.ownerRepository.findById(1);
String old = o1.getLastName();
@ -109,5 +98,4 @@ public abstract class AbstractOwnerRepositoryTests {
}
}

View file

@ -15,27 +15,23 @@
*/
package org.springframework.samples.petclinic.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.joda.time.DateTime;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <p>
* Base class for {@link OwnerRepository} integration tests.
* </p>
* <p>
* <p> Base class for {@link OwnerRepository} integration tests. </p>
* <p/>
* see javadoc inside {@link AbstractOwnerRepositoryTests} for more details
*
* @author Ken Krebs
@ -53,7 +49,8 @@ public abstract class AbstractPetRepositoryTests {
protected OwnerRepository ownerRepository;
@Test @Transactional
@Test
@Transactional
public void getPetTypes() {
Collection<PetType> petTypes = this.petRepository.findPetTypes();
@ -63,7 +60,8 @@ public abstract class AbstractPetRepositoryTests {
assertEquals("snake", petType4.getName());
}
@Test @Transactional
@Test
@Transactional
public void findPet() {
Collection<PetType> types = this.petRepository.findPetTypes();
Pet pet7 = this.petRepository.findById(7);
@ -76,7 +74,8 @@ public abstract class AbstractPetRepositoryTests {
assertEquals("Peter", pet6.getOwner().getFirstName());
}
@Test @Transactional
@Test
@Transactional
public void insertPet() {
Owner owner6 = this.ownerRepository.findById(6);
int found = owner6.getPets().size();
@ -94,7 +93,8 @@ public abstract class AbstractPetRepositoryTests {
assertEquals(found + 1, owner6.getPets().size());
}
@Test @Transactional
@Test
@Transactional
public void updatePet() throws Exception {
Pet pet7 = this.petRepository.findById(7);
String old = pet7.getName();

View file

@ -15,23 +15,19 @@
*/
package org.springframework.samples.petclinic.repository;
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.VetRepository;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
/**
* <p>
* Base class for {@link OwnerRepository} integration tests.
* </p>
* <p>
* <p> Base class for {@link OwnerRepository} integration tests. </p>
* <p/>
* see javadoc inside {@link AbstractVetRepositoryTests} for more details
*
* @author Ken Krebs
@ -46,7 +42,8 @@ public abstract class AbstractVetRepositoryTests {
protected VetRepository vetRepository;
@Test @Transactional
@Test
@Transactional
public void findVets() {
Collection<Vet> vets = this.vetRepository.findAll();

View file

@ -15,22 +15,17 @@
*/
package org.springframework.samples.petclinic.repository;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
/**
* <p>
* Base class for {@link OwnerRepository} integration tests.
* </p>
* <p>
* <p> Base class for {@link OwnerRepository} integration tests. </p>
* <p/>
* see javadoc inside {@link AbstractVetRepositoryTests} for more details
*
* @author Ken Krebs
@ -48,7 +43,8 @@ public abstract class AbstractVisitRepositoryTests {
protected PetRepository petRepository;
@Test @Transactional
@Test
@Transactional
public void insertVisit() {
Pet pet7 = this.petRepository.findById(7);
int found = pet7.getVisits().size();

View file

@ -22,20 +22,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jdbc")
public class JdbcOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jdbc")
public class JdbcPetRepositoryImplTests extends AbstractPetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jdbc")
public class JdbcVetRepositoryImplTests extends AbstractVetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jdbc")
public class JdbcVisitRepositoryImplTests extends AbstractVisitRepositoryTests {
}

View file

@ -8,25 +8,17 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Provides the following services:
* <ul>
* <li>Injects test dependencies, meaning that we don't need to perform
* application context lookups. See the setClinic() method. Injection uses
* autowiring by type.</li>
* <li>Executes each test method in its own transaction, which is automatically
* rolled back by default. This means that even if tests insert or otherwise
* change database state, there is no need for a teardown or cleanup script.</li>
* </ul>
* <p>
* </p>
* <p> Provides the following services: <ul> <li>Injects test dependencies, meaning that we don't need to perform
* application context lookups. See the setClinic() method. Injection uses autowiring by type.</li> <li>Executes each
* test method in its own transaction, which is automatically rolled back by default. This means that even if tests
* insert or otherwise change database state, there is no need for a teardown or cleanup script.</li> </ul> <p> </p>
*
* @author Rod Johnson
* @author Sam Brannen
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jpa")
public class JpaOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests {

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jpa")
public class JpaPetRepositoryImplTests extends AbstractPetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jpa")
public class JpaVetRepositoryImplTests extends AbstractVetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jpa")
public class JpaVisitRepositoryImplTests extends AbstractVisitRepositoryTests {
}

View file

@ -8,25 +8,17 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Provides the following services:
* <ul>
* <li>Injects test dependencies, meaning that we don't need to perform
* application context lookups. See the setClinic() method. Injection uses
* autowiring by type.</li>
* <li>Executes each test method in its own transaction, which is automatically
* rolled back by default. This means that even if tests insert or otherwise
* change database state, there is no need for a teardown or cleanup script.</li>
* </ul>
* <p>
* </p>
* <p> Provides the following services: <ul> <li>Injects test dependencies, meaning that we don't need to perform
* application context lookups. See the setClinic() method. Injection uses autowiring by type.</li> <li>Executes each
* test method in its own transaction, which is automatically rolled back by default. This means that even if tests
* insert or otherwise change database state, there is no need for a teardown or cleanup script.</li> </ul> <p> </p>
*
* @author Rod Johnson
* @author Sam Brannen
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("spring-data-jpa")
public class JpaOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests {

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("spring-data-jpa")
public class JpaPetRepositoryImplTests extends AbstractPetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("spring-data-jpa")
public class JpaVetRepositoryImplTests extends AbstractVetRepositoryTests {
}

View file

@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinicImpl} implementation.
* </p>
* <p>
* </p>
* <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("spring-data-jpa")
public class JpaVisitRepositoryImplTests extends AbstractVisitRepositoryTests {
}

View file

@ -11,7 +11,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Michael Isvy
*/
@ContextConfiguration(locations={"classpath:spring/dao-config.xml"})
@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("spring-data-jpa")
public class SpringDataOwnerRepositoryTests extends AbstractOwnerRepositoryTests {

View file

@ -16,14 +16,8 @@
package org.springframework.samples.petclinic.web;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
@ -31,8 +25,13 @@ import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.model.Visit;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Arjen Poutsma

View file

@ -2,8 +2,10 @@
<!--
- DispatcherServlet application context for PetClinic's web tier.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring/dao-config.xml"/>
<import resource="classpath:spring/mvc-core-config.xml"/>

View file

@ -16,12 +16,6 @@
package org.springframework.samples.petclinic.web;
import static org.hamcrest.Matchers.containsString;
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.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -36,6 +30,10 @@ import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author Arjen Poutsma
* @author Michael Isvy
@ -60,6 +58,7 @@ public class VisitsAtomViewWithContainerTest {
@Test
public void getVisits() throws Exception {
//gDickens: MediaType is not used
MediaType mediaType = MediaType.APPLICATION_ATOM_XML;
ResultActions actions = this.mockMvc.perform(get("/vets.atom"));
actions.andExpect(status().isOk());

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.samples.petclinic" level="debug"/>
<logger name="org.springframework.test.web" level="trace"/>
<root level="warn">
<appender-ref ref="console"/>
</root>
</configuration>