├── settings.gradle ├── .gitattributes ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ ├── maven-wrapper.properties │ └── MavenWrapperDownloader.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ ├── resources │ │ ├── messages │ │ │ ├── messages_en.properties │ │ │ ├── messages_ko.properties │ │ │ ├── messages.properties │ │ │ ├── messages_es.properties │ │ │ └── messages_de.properties │ │ ├── static │ │ │ └── resources │ │ │ │ ├── images │ │ │ │ ├── pets.png │ │ │ │ ├── favicon.png │ │ │ │ ├── spring-logo-dataflow.png │ │ │ │ ├── spring-logo-dataflow-mobile.png │ │ │ │ └── spring-logo.svg │ │ │ │ └── fonts │ │ │ │ ├── montserrat-webfont.eot │ │ │ │ ├── montserrat-webfont.ttf │ │ │ │ ├── montserrat-webfont.woff │ │ │ │ ├── varela_round-webfont.eot │ │ │ │ ├── varela_round-webfont.ttf │ │ │ │ └── varela_round-webfont.woff │ │ ├── db │ │ │ ├── mysql │ │ │ │ ├── user.sql │ │ │ │ ├── schema.sql │ │ │ │ ├── petclinic_db_setup_mysql.txt │ │ │ │ └── data.sql │ │ │ ├── postgres │ │ │ │ ├── petclinic_db_setup_postgres.txt │ │ │ │ ├── schema.sql │ │ │ │ └── data.sql │ │ │ ├── hsqldb │ │ │ │ ├── schema.sql │ │ │ │ └── data.sql │ │ │ └── h2 │ │ │ │ ├── schema.sql │ │ │ │ └── data.sql │ │ ├── application-postgres.properties │ │ ├── application-mysql.properties │ │ ├── templates │ │ │ ├── error.html │ │ │ ├── welcome.html │ │ │ ├── fragments │ │ │ │ ├── selectField.html │ │ │ │ ├── inputField.html │ │ │ │ └── layout.html │ │ │ ├── owners │ │ │ │ ├── findOwners.html │ │ │ │ ├── createOrUpdateOwnerForm.html │ │ │ │ ├── ownerDetails.html │ │ │ │ └── ownersList.html │ │ │ ├── pets │ │ │ │ ├── createOrUpdatePetForm.html │ │ │ │ └── createOrUpdateVisitForm.html │ │ │ └── vets │ │ │ │ └── vetList.html │ │ ├── banner.txt │ │ └── application.properties │ ├── scss │ │ ├── responsive.scss │ │ ├── header.scss │ │ ├── typography.scss │ │ └── petclinic.scss │ └── java │ │ └── org │ │ └── springframework │ │ └── samples │ │ └── petclinic │ │ ├── model │ │ ├── package-info.java │ │ ├── NamedEntity.java │ │ ├── BaseEntity.java │ │ └── Person.java │ │ ├── system │ │ ├── WelcomeController.java │ │ ├── CrashController.java │ │ └── CacheConfiguration.java │ │ ├── owner │ │ ├── PetType.java │ │ ├── Visit.java │ │ ├── PetValidator.java │ │ ├── PetTypeFormatter.java │ │ ├── Pet.java │ │ ├── OwnerRepository.java │ │ ├── VisitController.java │ │ ├── Owner.java │ │ ├── PetController.java │ │ └── OwnerController.java │ │ ├── vet │ │ ├── Specialty.java │ │ ├── Vets.java │ │ ├── VetRepository.java │ │ ├── Vet.java │ │ └── VetController.java │ │ ├── PetClinicApplication.java │ │ └── PetClinicRuntimeHints.java ├── checkstyle │ ├── nohttp-checkstyle.xml │ └── nohttp-checkstyle-suppressions.xml └── test │ └── java │ └── org │ └── springframework │ └── samples │ └── petclinic │ ├── vet │ ├── VetTests.java │ └── VetControllerTests.java │ ├── MysqlTestApplication.java │ ├── system │ ├── CrashControllerTests.java │ └── CrashControllerIntegrationTests.java │ ├── service │ ├── EntityUtils.java │ └── ClinicServiceTests.java │ ├── model │ └── ValidatorTests.java │ ├── PetClinicIntegrationTests.java │ ├── MySqlIntegrationTests.java │ ├── owner │ ├── PetTypeFormatterTests.java │ ├── VisitControllerTests.java │ └── PetControllerTests.java │ └── PostgresIntegrationTests.java ├── .gitignore ├── .gitpod.yml ├── .editorconfig ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── docker-compose.yml ├── .github └── workflows │ └── maven-build.yml ├── gradlew.bat ├── mvnw.cmd ├── gradlew └── readme.md /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-petclinic' 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | mvnw text eol=lf 2 | *.java text eol=lf 3 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/messages/messages_en.properties: -------------------------------------------------------------------------------- 1 | # This file is intentionally empty. Message look-ups will fall back to the default "messages.properties" file. -------------------------------------------------------------------------------- /src/main/resources/static/resources/images/pets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/images/pets.png -------------------------------------------------------------------------------- /src/main/resources/static/resources/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/images/favicon.png -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/montserrat-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/montserrat-webfont.eot -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/montserrat-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/montserrat-webfont.ttf -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/montserrat-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/montserrat-webfont.woff -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/varela_round-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/varela_round-webfont.eot -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/varela_round-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/varela_round-webfont.ttf -------------------------------------------------------------------------------- /src/main/resources/static/resources/fonts/varela_round-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/fonts/varela_round-webfont.woff -------------------------------------------------------------------------------- /src/main/resources/static/resources/images/spring-logo-dataflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/images/spring-logo-dataflow.png -------------------------------------------------------------------------------- /src/main/resources/static/resources/images/spring-logo-dataflow-mobile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/spring-petclinic/HEAD/src/main/resources/static/resources/images/spring-logo-dataflow-mobile.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/* 2 | bin/* 3 | build/* 4 | .gradle/* 5 | .settings/* 6 | .classpath 7 | .project 8 | .factorypath 9 | .attach_pid* 10 | .idea 11 | *.iml 12 | /target 13 | .sts4-cache/ 14 | .vscode 15 | _site/ 16 | *.css 17 | !petclinic.css 18 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar 3 | -------------------------------------------------------------------------------- /src/main/resources/db/mysql/user.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS petclinic; 2 | 3 | ALTER DATABASE petclinic 4 | DEFAULT CHARACTER SET utf8 5 | DEFAULT COLLATE utf8_general_ci; 6 | 7 | GRANT ALL PRIVILEGES ON petclinic.* TO 'petclinic'@'%' IDENTIFIED BY 'petclinic'; 8 | -------------------------------------------------------------------------------- /src/main/resources/messages/messages_ko.properties: -------------------------------------------------------------------------------- 1 | welcome=환영합니다 2 | required=입력이 필요합니다 3 | notFound=찾을 수 없습니다 4 | duplicate=이미 존재합니다 5 | nonNumeric=모두 숫자로 입력해야 합니다 6 | duplicateFormSubmission=중복 제출은 허용되지 않습니다 7 | typeMismatch.date=잘못된 날짜입니다 8 | typeMismatch.birthDate=잘못된 날짜입니다 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: ./.devcontainer/Dockerfile 3 | tasks: 4 | - before: sudo usermod -a -G sdkman gitpod && sudo usermod -a -G nvm gitpod && sudo chown -R gitpod /usr/local/sdkman /usr/local/share/nvm 5 | - init: ./mvnw install 6 | vscode: 7 | extensions: 8 | - vscjava.vscode-java-pack 9 | - redhat.vscode-xml -------------------------------------------------------------------------------- /src/main/resources/messages/messages.properties: -------------------------------------------------------------------------------- 1 | welcome=Welcome 2 | required=is required 3 | notFound=has not been found 4 | duplicate=is already in use 5 | nonNumeric=must be all numeric 6 | duplicateFormSubmission=Duplicate form submission is not allowed 7 | typeMismatch.date=invalid date 8 | typeMismatch.birthDate=invalid date 9 | -------------------------------------------------------------------------------- /src/checkstyle/nohttp-checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/main/resources/application-postgres.properties: -------------------------------------------------------------------------------- 1 | database=postgres 2 | spring.datasource.url=${POSTGRES_URL:jdbc:postgresql://localhost/petclinic} 3 | spring.datasource.username=${POSTGRES_USER:petclinic} 4 | spring.datasource.password=${POSTGRES_PASS:petclinic} 5 | # SQL is written to be idempotent so this is safe 6 | spring.sql.init.mode=always 7 | -------------------------------------------------------------------------------- /src/main/resources/application-mysql.properties: -------------------------------------------------------------------------------- 1 | # database init, supports mysql too 2 | database=mysql 3 | spring.datasource.url=${MYSQL_URL:jdbc:mysql://localhost/petclinic} 4 | spring.datasource.username=${MYSQL_USER:petclinic} 5 | spring.datasource.password=${MYSQL_PASS:petclinic} 6 | # SQL is written to be idempotent so this is safe 7 | spring.sql.init.mode=always 8 | -------------------------------------------------------------------------------- /src/main/resources/messages/messages_es.properties: -------------------------------------------------------------------------------- 1 | welcome=Bienvenido 2 | required=Es requerido 3 | notFound=No ha sido encontrado 4 | duplicate=Ya se encuentra en uso 5 | nonNumeric=Sólo debe contener numeros 6 | duplicateFormSubmission=No se permite el envío de formularios duplicados 7 | typeMismatch.date=Fecha invalida 8 | typeMismatch.birthDate=Fecha invalida 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/messages/messages_de.properties: -------------------------------------------------------------------------------- 1 | welcome=Willkommen 2 | required=muss angegeben werden 3 | notFound=wurde nicht gefunden 4 | duplicate=ist bereits vergeben 5 | nonNumeric=darf nur numerisch sein 6 | duplicateFormSubmission=Wiederholtes Absenden des Formulars ist nicht erlaubt 7 | typeMismatch.date=ung�ltiges Datum 8 | typeMismatch.birthDate=ung�ltiges Datum 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/templates/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Something happened...

8 |

Exception message

9 | 10 | 11 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = space 9 | 10 | [*.{java,xml}] 11 | indent_size = 4 12 | trim_trailing_whitespace = true 13 | indent_style = tab 14 | tab_width = 4 15 | 16 | [{pom,wro}.xml] 17 | indent_size = 2 18 | indent_style = space 19 | 20 | [*.{html,sql,less}] 21 | indent_size = 2 22 | -------------------------------------------------------------------------------- /src/main/resources/templates/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Welcome

8 |
9 |
10 | 11 |
12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/checkstyle/nohttp-checkstyle-suppressions.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG VARIANT=17-bullseye 2 | FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT} 3 | 4 | ARG NODE_VERSION="none" 5 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 6 | 7 | ARG USER=vscode 8 | VOLUME /home/$USER/.m2 9 | VOLUME /home/$USER/.gradle 10 | 11 | ARG JAVA_VERSION=17.0.7-ms 12 | RUN sudo mkdir /home/$USER/.m2 /home/$USER/.gradle && sudo chown $USER:$USER /home/$USER/.m2 /home/$USER/.gradle 13 | RUN bash -lc '. /usr/local/sdkman/bin/sdkman-init.sh && sdk install java $JAVA_VERSION && sdk use java $JAVA_VERSION' 14 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "2.2" 2 | 3 | services: 4 | mysql: 5 | image: mysql:8.2 6 | ports: 7 | - "3306:3306" 8 | environment: 9 | - MYSQL_ROOT_PASSWORD= 10 | - MYSQL_ALLOW_EMPTY_PASSWORD=true 11 | - MYSQL_USER=petclinic 12 | - MYSQL_PASSWORD=petclinic 13 | - MYSQL_DATABASE=petclinic 14 | volumes: 15 | - "./conf.d:/etc/mysql/conf.d:ro" 16 | profiles: 17 | - mysql 18 | postgres: 19 | image: postgres:16.1 20 | ports: 21 | - "5432:5432" 22 | environment: 23 | - POSTGRES_PASSWORD=petclinic 24 | - POSTGRES_USER=petclinic 25 | - POSTGRES_DB=petclinic 26 | profiles: 27 | - postgres 28 | -------------------------------------------------------------------------------- /src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | |\ _,,,--,,_ 4 | /,`.-'`' ._ \-;;,_ 5 | _______ __|,4- ) )_ .;.(__`'-'__ ___ __ _ ___ _______ 6 | | | '---''(_/._)-'(_\_) | | | | | | | | | 7 | | _ | ___|_ _| | | | | |_| | | | __ _ _ 8 | | |_| | |___ | | | | | | | | | | \ \ \ \ 9 | | ___| ___| | | | _| |___| | _ | | _| \ \ \ \ 10 | | | | |___ | | | |_| | | | | | | |_ ) ) ) ) 11 | |___| |_______| |___| |_______|_______|___|_| |__|___|_______| / / / / 12 | ==================================================================/_/_/_/ 13 | 14 | :: Built with Spring Boot :: ${spring-boot.version} 15 | 16 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # database init, supports mysql too 2 | database=h2 3 | spring.sql.init.schema-locations=classpath*:db/${database}/schema.sql 4 | spring.sql.init.data-locations=classpath*:db/${database}/data.sql 5 | 6 | # Web 7 | spring.thymeleaf.mode=HTML 8 | 9 | # JPA 10 | spring.jpa.hibernate.ddl-auto=none 11 | spring.jpa.open-in-view=true 12 | 13 | # Internationalization 14 | spring.messages.basename=messages/messages 15 | 16 | # Actuator 17 | management.endpoints.web.exposure.include=* 18 | 19 | # Logging 20 | logging.level.org.springframework=INFO 21 | # logging.level.org.springframework.web=DEBUG 22 | # logging.level.org.springframework.context.annotation=TRACE 23 | 24 | # Maximum time static resources should be cached 25 | spring.web.resources.cache.cachecontrol.max-age=12h 26 | -------------------------------------------------------------------------------- /src/main/scss/responsive.scss: -------------------------------------------------------------------------------- 1 | @media (max-width: 768px) { 2 | .navbar-toggle { 3 | position:absolute; 4 | z-index: 9999; 5 | left:0px; 6 | top:0px; 7 | } 8 | 9 | .navbar a.navbar-brand { 10 | display: block; 11 | margin: 0 auto 0 auto; 12 | width: 148px; 13 | height: 50px; 14 | float: none; 15 | background: url("../images/spring-logo-dataflow-mobile.png") 0 center no-repeat; 16 | } 17 | 18 | .homepage-billboard .homepage-subtitle { 19 | font-size: 21px; 20 | line-height: 21px; 21 | } 22 | 23 | .navbar a.navbar-brand span { 24 | display: none; 25 | } 26 | 27 | .navbar { 28 | border-top-width: 0; 29 | } 30 | 31 | .xd-container { 32 | margin-top: 20px; 33 | margin-bottom: 30px; 34 | } 35 | 36 | .index-page--subtitle { 37 | margin-top: 10px; 38 | margin-bottom: 30px; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/model/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * The classes in this package represent utilities used by the domain. 19 | */ 20 | package org.springframework.samples.petclinic.model; 21 | -------------------------------------------------------------------------------- /.github/workflows/maven-build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | java: [ '17' ] 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Set up JDK ${{matrix.java}} 23 | uses: actions/setup-java@v2 24 | with: 25 | java-version: ${{matrix.java}} 26 | distribution: 'adopt' 27 | cache: maven 28 | - name: Build with Maven Wrapper 29 | run: ./mvnw -B package 30 | -------------------------------------------------------------------------------- /src/main/resources/db/postgres/petclinic_db_setup_postgres.txt: -------------------------------------------------------------------------------- 1 | =============================================================================== 2 | === Spring PetClinic sample application - PostgreSQL Configuration === 3 | =============================================================================== 4 | 5 | -------------------------------------------------------------------------------- 6 | 7 | 1) Run the "docker-compose.yml" from the root of the project: 8 | 9 | $ docker-compose up 10 | ... 11 | spring-petclinic-postgres-1 | The files belonging to this database system will be owned by user "postgres". 12 | ... 13 | 14 | 2) Run the app with `spring.profiles.active=postgres` (e.g. as a System property via the command 15 | line, but any way that sets that property in a Spring Boot app should work). For example use 16 | 17 | mvn spring-boot:run -Dspring-boot.run.profiles=postgres 18 | 19 | To activate the profile on the command line. 20 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Petclinic", 3 | "dockerFile": "Dockerfile", 4 | "runArgs": [ 5 | "--cap-add=SYS_PTRACE", 6 | "--security-opt", 7 | "seccomp=unconfined", 8 | "--mount", 9 | "type=bind,source=${env:HOME}/.m2,target=/home/vscode/.m2", 10 | "--mount", 11 | "type=bind,source=${env:HOME}/.gradle,target=/home/vscode/.gradle", 12 | "--env", 13 | "GRADLE_USER_HOME=/home/vscode/.gradle" 14 | ], 15 | "initializeCommand": "mkdir -p ${env:HOME}/.m2 ${env:HOME}/.gradle", 16 | "postCreateCommand": "sudo chown vscode:vscode /home/vscode/.m2 /home/vscode/.gradle", 17 | "remoteUser": "vscode", 18 | "features": { 19 | "docker-in-docker": "latest" 20 | }, 21 | "extensions": [ 22 | "vscjava.vscode-java-pack", 23 | "redhat.vscode-xml", 24 | "vmware.vscode-boot-dev-pack", 25 | "mhutchie.git-graph" 26 | ], 27 | "forwardPorts": [8080], 28 | "settings": { 29 | "java.import.gradle.enabled": false, 30 | "java.server.launchMode": "Standard" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.system; 18 | 19 | import org.springframework.stereotype.Controller; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | 22 | @Controller 23 | class WelcomeController { 24 | 25 | @GetMapping("/") 26 | public String welcome() { 27 | return "welcome"; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/templates/fragments/selectField.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
8 | 9 | 10 |
11 | 15 | 18 | 19 | 22 | Error 23 | 24 |
25 |
26 |
27 |
28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/PetType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import org.springframework.samples.petclinic.model.NamedEntity; 19 | 20 | import jakarta.persistence.Entity; 21 | import jakarta.persistence.Table; 22 | 23 | /** 24 | * @author Juergen Hoeller Can be Cat, Dog, Hamster... 25 | */ 26 | @Entity 27 | @Table(name = "types") 28 | public class PetType extends NamedEntity { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/vet/Specialty.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import org.springframework.samples.petclinic.model.NamedEntity; 19 | 20 | import jakarta.persistence.Entity; 21 | import jakarta.persistence.Table; 22 | 23 | /** 24 | * Models a {@link Vet Vet's} specialty (for example, dentistry). 25 | * 26 | * @author Juergen Hoeller 27 | */ 28 | @Entity 29 | @Table(name = "specialties") 30 | public class Specialty extends NamedEntity { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/resources/templates/fragments/inputField.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
8 | 9 |
10 |
11 | 12 | 13 |
14 | 17 | 18 | 21 | Error 22 | 23 |
24 |
25 |
26 |
27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/resources/templates/owners/findOwners.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 |

Find Owners

7 | 8 |
10 |
11 |
12 | 13 |
14 |
17 |

Error

18 |
19 |
20 |
21 |
22 |
23 |
24 | 26 |
27 |
28 | 29 | Add Owner 30 | 31 |
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/main/resources/templates/owners/createOrUpdateOwnerForm.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 |

Owner

7 |
8 |
9 | 11 | 13 | 15 | 17 | 19 |
20 |
21 |
22 | 26 |
27 |
28 |
29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.context.annotation.ImportRuntimeHints; 22 | 23 | /** 24 | * PetClinic Spring Boot Application. 25 | * 26 | * @author Dave Syer 27 | * 28 | */ 29 | @SpringBootApplication 30 | @ImportRuntimeHints(PetClinicRuntimeHints.class) 31 | public class PetClinicApplication { 32 | 33 | public static void main(String[] args) { 34 | SpringApplication.run(PetClinicApplication.class, args); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/resources/templates/pets/createOrUpdatePetForm.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 |

7 | New 8 | Pet 9 |

10 |
11 | 12 |
13 |
14 | 15 |
16 | 17 |
18 |
19 | 21 | 23 | 25 |
26 |
27 |
28 | 32 |
33 |
34 |
35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/system/CrashController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.system; 17 | 18 | import org.springframework.stereotype.Controller; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | 21 | /** 22 | * Controller used to showcase what happens when an exception is thrown 23 | * 24 | * @author Michael Isvy 25 | *

26 | * Also see how a view that resolves to "error" has been added ("error.html"). 27 | */ 28 | @Controller 29 | class CrashController { 30 | 31 | @GetMapping("/oups") 32 | public String triggerException() { 33 | throw new RuntimeException( 34 | "Expected: controller used to showcase what " + "happens when an exception is thrown"); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/vet/Vets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | import jakarta.xml.bind.annotation.XmlElement; 22 | import jakarta.xml.bind.annotation.XmlRootElement; 23 | 24 | /** 25 | * Simple domain object representing a list of veterinarians. Mostly here to be used for 26 | * the 'vets' {@link org.springframework.web.servlet.view.xml.MarshallingView}. 27 | * 28 | * @author Arjen Poutsma 29 | */ 30 | @XmlRootElement 31 | public class Vets { 32 | 33 | private List vets; 34 | 35 | @XmlElement 36 | public List getVetList() { 37 | if (vets == null) { 38 | vets = new ArrayList<>(); 39 | } 40 | return vets; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.model; 17 | 18 | import jakarta.persistence.Column; 19 | import jakarta.persistence.MappedSuperclass; 20 | 21 | /** 22 | * Simple JavaBean domain object adds a name property to BaseEntity. Used as 23 | * a base class for objects needing these properties. 24 | * 25 | * @author Ken Krebs 26 | * @author Juergen Hoeller 27 | */ 28 | @MappedSuperclass 29 | public class NamedEntity extends BaseEntity { 30 | 31 | @Column(name = "name") 32 | private String name; 33 | 34 | public String getName() { 35 | return this.name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return this.getName(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/vet/VetTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import org.junit.jupiter.api.Test; 19 | import org.springframework.util.SerializationUtils; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | 23 | /** 24 | * @author Dave Syer 25 | */ 26 | class VetTests { 27 | 28 | @Test 29 | void testSerialization() { 30 | Vet vet = new Vet(); 31 | vet.setFirstName("Zaphod"); 32 | vet.setLastName("Beeblebrox"); 33 | vet.setId(123); 34 | @SuppressWarnings("deprecation") 35 | Vet other = (Vet) SerializationUtils.deserialize(SerializationUtils.serialize(vet)); 36 | assertThat(other.getFirstName()).isEqualTo(vet.getFirstName()); 37 | assertThat(other.getLastName()).isEqualTo(vet.getLastName()); 38 | assertThat(other.getId()).isEqualTo(vet.getId()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.model; 17 | 18 | import java.io.Serializable; 19 | 20 | import jakarta.persistence.GeneratedValue; 21 | import jakarta.persistence.GenerationType; 22 | import jakarta.persistence.Id; 23 | import jakarta.persistence.MappedSuperclass; 24 | 25 | /** 26 | * Simple JavaBean domain object with an id property. Used as a base class for objects 27 | * needing this property. 28 | * 29 | * @author Ken Krebs 30 | * @author Juergen Hoeller 31 | */ 32 | @MappedSuperclass 33 | public class BaseEntity implements Serializable { 34 | 35 | @Id 36 | @GeneratedValue(strategy = GenerationType.IDENTITY) 37 | private Integer id; 38 | 39 | public Integer getId() { 40 | return id; 41 | } 42 | 43 | public void setId(Integer id) { 44 | this.id = id; 45 | } 46 | 47 | public boolean isNew() { 48 | return this.id == null; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/resources/db/postgres/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS vets ( 2 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 3 | first_name TEXT, 4 | last_name TEXT 5 | ); 6 | CREATE INDEX ON vets (last_name); 7 | 8 | CREATE TABLE IF NOT EXISTS specialties ( 9 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 10 | name TEXT 11 | ); 12 | CREATE INDEX ON specialties (name); 13 | 14 | CREATE TABLE IF NOT EXISTS vet_specialties ( 15 | vet_id INT NOT NULL REFERENCES vets (id), 16 | specialty_id INT NOT NULL REFERENCES specialties (id), 17 | UNIQUE (vet_id, specialty_id) 18 | ); 19 | 20 | CREATE TABLE IF NOT EXISTS types ( 21 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 22 | name TEXT 23 | ); 24 | CREATE INDEX ON types (name); 25 | 26 | CREATE TABLE IF NOT EXISTS owners ( 27 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 28 | first_name TEXT, 29 | last_name TEXT, 30 | address TEXT, 31 | city TEXT, 32 | telephone TEXT 33 | ); 34 | CREATE INDEX ON owners (last_name); 35 | 36 | CREATE TABLE IF NOT EXISTS pets ( 37 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 38 | name TEXT, 39 | birth_date DATE, 40 | type_id INT NOT NULL REFERENCES types (id), 41 | owner_id INT REFERENCES owners (id) 42 | ); 43 | CREATE INDEX ON pets (name); 44 | CREATE INDEX ON pets (owner_id); 45 | 46 | CREATE TABLE IF NOT EXISTS visits ( 47 | id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 48 | pet_id INT REFERENCES pets (id), 49 | visit_date DATE, 50 | description TEXT 51 | ); 52 | CREATE INDEX ON visits (pet_id); 53 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/model/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.model; 17 | 18 | import jakarta.persistence.Column; 19 | import jakarta.persistence.MappedSuperclass; 20 | import jakarta.validation.constraints.NotBlank; 21 | 22 | /** 23 | * Simple JavaBean domain object representing an person. 24 | * 25 | * @author Ken Krebs 26 | */ 27 | @MappedSuperclass 28 | public class Person extends BaseEntity { 29 | 30 | @Column(name = "first_name") 31 | @NotBlank 32 | private String firstName; 33 | 34 | @Column(name = "last_name") 35 | @NotBlank 36 | private String lastName; 37 | 38 | public String getFirstName() { 39 | return this.firstName; 40 | } 41 | 42 | public void setFirstName(String firstName) { 43 | this.firstName = firstName; 44 | } 45 | 46 | public String getLastName() { 47 | return this.lastName; 48 | } 49 | 50 | public void setLastName(String lastName) { 51 | this.lastName = lastName; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/MysqlTestApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Configuration; 23 | import org.springframework.context.annotation.Profile; 24 | import org.testcontainers.containers.MySQLContainer; 25 | 26 | /** 27 | * PetClinic Spring Boot Application. 28 | * 29 | * @author Dave Syer 30 | * 31 | */ 32 | @Configuration 33 | public class MysqlTestApplication { 34 | 35 | @ServiceConnection 36 | @Profile("mysql") 37 | @Bean 38 | static MySQLContainer container() { 39 | return new MySQLContainer<>("mysql:8.2"); 40 | } 41 | 42 | public static void main(String[] args) { 43 | SpringApplication.run(PetClinicApplication.class, "--spring.profiles.active=mysql"); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.system; 18 | 19 | import static org.junit.jupiter.api.Assertions.assertEquals; 20 | import static org.junit.jupiter.api.Assertions.assertThrows; 21 | 22 | import org.junit.jupiter.api.Test; 23 | 24 | /** 25 | * Test class for {@link CrashController} 26 | * 27 | * @author Colin But 28 | * @author Alex Lutz 29 | */ 30 | // Waiting https://github.com/spring-projects/spring-boot/issues/5574 ..good 31 | // luck ((plain(st) UNIT test)! :) 32 | class CrashControllerTests { 33 | 34 | CrashController testee = new CrashController(); 35 | 36 | @Test 37 | void testTriggerException() throws Exception { 38 | RuntimeException thrown = assertThrows(RuntimeException.class, () -> { 39 | testee.triggerException(); 40 | }); 41 | 42 | assertEquals("Expected: controller used to showcase what happens when an exception is thrown", 43 | thrown.getMessage()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/scss/header.scss: -------------------------------------------------------------------------------- 1 | .navbar { 2 | border-top: 4px solid #6db33f; 3 | background-color: #34302d; 4 | margin-bottom: 0px; 5 | border-bottom: 0; 6 | border-left: 0; 7 | border-right: 0; 8 | } 9 | 10 | .navbar a.navbar-brand { 11 | background: url("../images/spring-logo-dataflow.png") -1px -1px no-repeat; 12 | margin: 12px 0 6px; 13 | width: 229px; 14 | height: 46px; 15 | display: inline-block; 16 | text-decoration: none; 17 | padding: 0; 18 | } 19 | 20 | .navbar a.navbar-brand span { 21 | display: block; 22 | width: 229px; 23 | height: 46px; 24 | background: url("../images/spring-logo-dataflow.png") -1px -48px no-repeat; 25 | opacity: 0; 26 | -moz-transition: opacity 0.12s ease-in-out; 27 | -webkit-transition: opacity 0.12s ease-in-out; 28 | -o-transition: opacity 0.12s ease-in-out; 29 | } 30 | 31 | .navbar a:hover.navbar-brand span { 32 | opacity: 1; 33 | } 34 | 35 | .navbar li > a, .navbar-text { 36 | font-family: "montserratregular", sans-serif; 37 | text-shadow: none; 38 | font-size: 14px; 39 | 40 | /* line-height: 14px; */ 41 | padding: 28px 20px; 42 | transition: all 0.15s; 43 | -webkit-transition: all 0.15s; 44 | -moz-transition: all 0.15s; 45 | -o-transition: all 0.15s; 46 | -ms-transition: all 0.15s; 47 | } 48 | 49 | .navbar li > a { 50 | text-transform: uppercase; 51 | } 52 | 53 | .navbar .navbar-text { 54 | margin-top: 0; 55 | margin-bottom: 0; 56 | } 57 | .navbar li:hover > a { 58 | color: #eeeeee; 59 | background-color: #6db33f; 60 | } 61 | 62 | .navbar-toggle { 63 | border-width: 0; 64 | 65 | .icon-bar + .icon-bar { 66 | margin-top: 3px; 67 | } 68 | .icon-bar { 69 | width: 19px; 70 | height: 3px; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/scss/typography.scss: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: 'varela_roundregular'; 3 | 4 | src: url('../fonts/varela_round-webfont.eot'); 5 | src: url('../fonts/varela_round-webfont.eot?#iefix') format('embedded-opentype'), 6 | url('../fonts/varela_round-webfont.woff') format('woff'), 7 | url('../fonts/varela_round-webfont.ttf') format('truetype'), 8 | url('../fonts/varela_round-webfont.svg#varela_roundregular') format('svg'); 9 | font-weight: normal; 10 | font-style: normal; 11 | } 12 | 13 | @font-face { 14 | font-family: 'montserratregular'; 15 | src: url('../fonts/montserrat-webfont.eot'); 16 | src: url('../fonts/montserrat-webfont.eot?#iefix') format('embedded-opentype'), 17 | url('../fonts/montserrat-webfont.woff') format('woff'), 18 | url('../fonts/montserrat-webfont.ttf') format('truetype'), 19 | url('../fonts/montserrat-webfont.svg#montserratregular') format('svg'); 20 | font-weight: normal; 21 | font-style: normal; 22 | } 23 | 24 | body, h1, h2, h3, p, input { 25 | margin: 0; 26 | font-weight: 400; 27 | font-family: "varela_roundregular", sans-serif; 28 | color: #34302d; 29 | } 30 | 31 | h1 { 32 | font-size: 24px; 33 | line-height: 30px; 34 | font-family: "montserratregular", sans-serif; 35 | } 36 | 37 | h2 { 38 | font-size: 18px; 39 | font-weight: 700; 40 | line-height: 24px; 41 | margin-bottom: 10px; 42 | font-family: "montserratregular", sans-serif; 43 | } 44 | 45 | h3 { 46 | font-size: 16px; 47 | line-height: 24px; 48 | margin-bottom: 10px; 49 | font-weight: 700; 50 | } 51 | 52 | p { 53 | //font-size: 15px; 54 | //line-height: 24px; 55 | } 56 | 57 | strong { 58 | font-weight: 700; 59 | font-family: "montserratregular", sans-serif; 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/PetClinicRuntimeHints.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import org.springframework.aot.hint.RuntimeHints; 20 | import org.springframework.aot.hint.RuntimeHintsRegistrar; 21 | import org.springframework.samples.petclinic.model.BaseEntity; 22 | import org.springframework.samples.petclinic.model.Person; 23 | import org.springframework.samples.petclinic.vet.Vet; 24 | 25 | public class PetClinicRuntimeHints implements RuntimeHintsRegistrar { 26 | 27 | @Override 28 | public void registerHints(RuntimeHints hints, ClassLoader classLoader) { 29 | hints.resources().registerPattern("db/*"); // https://github.com/spring-projects/spring-boot/issues/32654 30 | hints.resources().registerPattern("messages/*"); 31 | hints.resources().registerPattern("META-INF/resources/webjars/*"); 32 | hints.resources().registerPattern("mysql-default-conf"); 33 | hints.serialization().registerType(BaseEntity.class); 34 | hints.serialization().registerType(Person.class); 35 | hints.serialization().registerType(Vet.class); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/resources/db/mysql/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS vets ( 2 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | first_name VARCHAR(30), 4 | last_name VARCHAR(30), 5 | INDEX(last_name) 6 | ) engine=InnoDB; 7 | 8 | CREATE TABLE IF NOT EXISTS specialties ( 9 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 10 | name VARCHAR(80), 11 | INDEX(name) 12 | ) engine=InnoDB; 13 | 14 | CREATE TABLE IF NOT EXISTS vet_specialties ( 15 | vet_id INT(4) UNSIGNED NOT NULL, 16 | specialty_id INT(4) UNSIGNED NOT NULL, 17 | FOREIGN KEY (vet_id) REFERENCES vets(id), 18 | FOREIGN KEY (specialty_id) REFERENCES specialties(id), 19 | UNIQUE (vet_id,specialty_id) 20 | ) engine=InnoDB; 21 | 22 | CREATE TABLE IF NOT EXISTS types ( 23 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 24 | name VARCHAR(80), 25 | INDEX(name) 26 | ) engine=InnoDB; 27 | 28 | CREATE TABLE IF NOT EXISTS owners ( 29 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 30 | first_name VARCHAR(30), 31 | last_name VARCHAR(30), 32 | address VARCHAR(255), 33 | city VARCHAR(80), 34 | telephone VARCHAR(20), 35 | INDEX(last_name) 36 | ) engine=InnoDB; 37 | 38 | CREATE TABLE IF NOT EXISTS pets ( 39 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 40 | name VARCHAR(30), 41 | birth_date DATE, 42 | type_id INT(4) UNSIGNED NOT NULL, 43 | owner_id INT(4) UNSIGNED, 44 | INDEX(name), 45 | FOREIGN KEY (owner_id) REFERENCES owners(id), 46 | FOREIGN KEY (type_id) REFERENCES types(id) 47 | ) engine=InnoDB; 48 | 49 | CREATE TABLE IF NOT EXISTS visits ( 50 | id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 51 | pet_id INT(4) UNSIGNED, 52 | visit_date DATE, 53 | description VARCHAR(255), 54 | FOREIGN KEY (pet_id) REFERENCES pets(id) 55 | ) engine=InnoDB; 56 | -------------------------------------------------------------------------------- /src/main/resources/db/mysql/petclinic_db_setup_mysql.txt: -------------------------------------------------------------------------------- 1 | ================================================================================ 2 | === Spring PetClinic sample application - MySQL Configuration === 3 | ================================================================================ 4 | 5 | @author Sam Brannen 6 | @author Costin Leau 7 | @author Dave Syer 8 | 9 | -------------------------------------------------------------------------------- 10 | 11 | 1) Download and install the MySQL database (e.g., MySQL Community Server 5.1.x), 12 | which can be found here: https://dev.mysql.com/downloads/. Or run the 13 | "docker-compose.yml" from the root of the project (if you have docker installed 14 | locally): 15 | 16 | $ docker-compose up 17 | ... 18 | mysql_1_eedb4818d817 | MySQL init process done. Ready for start up. 19 | ... 20 | 21 | 2) (Once only) create the PetClinic database and user by executing the "db/mysql/user.sql" 22 | scripts. You can connect to the database running in the docker container using 23 | `mysql -u root -h localhost --protocol tcp`, but you don't need to run the script there 24 | because the petclinic user is already set up if you use the provided `docker-compose.yml`. 25 | 26 | 3) Run the app with `spring.profiles.active=mysql` (e.g. as a System property via the command 27 | line, but any way that sets that property in a Spring Boot app should work). For example use 28 | 29 | mvn spring-boot:run -Dspring-boot.run.profiles=mysql 30 | 31 | To activate the profile on the command line. 32 | 33 | N.B. the "petclinic" database has to exist for the app to work with the JDBC URL value 34 | as it is configured by default. This condition is taken care of automatically by the 35 | docker-compose configuration provided, or by the `user.sql` script if you run that as 36 | root. 37 | -------------------------------------------------------------------------------- /src/main/resources/templates/pets/createOrUpdateVisitForm.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 |

7 | New 8 | Visit 9 |

10 | 11 | Pet 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 26 | 28 | 29 |
NameBirth DateTypeOwner
30 | 31 |
32 |
33 | 35 | 37 |
38 | 39 |
40 |
41 | 42 | 43 |
44 |
45 |
46 | 47 |
48 | Previous Visits 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |
DateDescription
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/Visit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.time.LocalDate; 19 | 20 | import org.springframework.format.annotation.DateTimeFormat; 21 | import org.springframework.samples.petclinic.model.BaseEntity; 22 | 23 | import jakarta.persistence.Column; 24 | import jakarta.persistence.Entity; 25 | import jakarta.persistence.Table; 26 | import jakarta.validation.constraints.NotBlank; 27 | 28 | /** 29 | * Simple JavaBean domain object representing a visit. 30 | * 31 | * @author Ken Krebs 32 | * @author Dave Syer 33 | */ 34 | @Entity 35 | @Table(name = "visits") 36 | public class Visit extends BaseEntity { 37 | 38 | @Column(name = "visit_date") 39 | @DateTimeFormat(pattern = "yyyy-MM-dd") 40 | private LocalDate date; 41 | 42 | @NotBlank 43 | private String description; 44 | 45 | /** 46 | * Creates a new instance of Visit for the current date 47 | */ 48 | public Visit() { 49 | this.date = LocalDate.now(); 50 | } 51 | 52 | public LocalDate getDate() { 53 | return this.date; 54 | } 55 | 56 | public void setDate(LocalDate date) { 57 | this.date = date; 58 | } 59 | 60 | public String getDescription() { 61 | return this.description; 62 | } 63 | 64 | public void setDescription(String description) { 65 | this.description = description; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/PetValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import org.springframework.util.StringUtils; 19 | import org.springframework.validation.Errors; 20 | import org.springframework.validation.Validator; 21 | 22 | /** 23 | * Validator for Pet forms. 24 | *

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

28 | * 29 | * @author Ken Krebs 30 | * @author Juergen Hoeller 31 | */ 32 | public class PetValidator implements Validator { 33 | 34 | private static final String REQUIRED = "required"; 35 | 36 | @Override 37 | public void validate(Object obj, Errors errors) { 38 | Pet pet = (Pet) obj; 39 | String name = pet.getName(); 40 | // name validation 41 | if (!StringUtils.hasText(name)) { 42 | errors.rejectValue("name", REQUIRED, REQUIRED); 43 | } 44 | 45 | // type validation 46 | if (pet.isNew() && pet.getType() == null) { 47 | errors.rejectValue("type", REQUIRED, REQUIRED); 48 | } 49 | 50 | // birth date validation 51 | if (pet.getBirthDate() == null) { 52 | errors.rejectValue("birthDate", REQUIRED, REQUIRED); 53 | } 54 | } 55 | 56 | /** 57 | * This Validator validates *just* Pet instances 58 | */ 59 | @Override 60 | public boolean supports(Class clazz) { 61 | return Pet.class.isAssignableFrom(clazz); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/service/EntityUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.service; 18 | 19 | import org.springframework.orm.ObjectRetrievalFailureException; 20 | import org.springframework.samples.petclinic.model.BaseEntity; 21 | 22 | import java.util.Collection; 23 | 24 | /** 25 | * Utility methods for handling entities. Separate from the BaseEntity class mainly 26 | * because of dependency on the ORM-associated ObjectRetrievalFailureException. 27 | * 28 | * @author Juergen Hoeller 29 | * @author Sam Brannen 30 | * @see org.springframework.samples.petclinic.model.BaseEntity 31 | * @since 29.10.2003 32 | */ 33 | public abstract class EntityUtils { 34 | 35 | /** 36 | * Look up the entity of the given class with the given id in the given collection. 37 | * @param entities the collection to search 38 | * @param entityClass the entity class to look up 39 | * @param entityId the entity id to look up 40 | * @return the found entity 41 | * @throws ObjectRetrievalFailureException if the entity was not found 42 | */ 43 | public static T getById(Collection entities, Class entityClass, int entityId) 44 | throws ObjectRetrievalFailureException { 45 | for (T entity : entities) { 46 | if (entity.getId() == entityId && entityClass.isInstance(entity)) { 47 | return entity; 48 | } 49 | } 50 | throw new ObjectRetrievalFailureException(entityClass, entityId); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/resources/db/hsqldb/schema.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE vet_specialties IF EXISTS; 2 | DROP TABLE vets IF EXISTS; 3 | DROP TABLE specialties IF EXISTS; 4 | DROP TABLE visits IF EXISTS; 5 | DROP TABLE pets IF EXISTS; 6 | DROP TABLE types IF EXISTS; 7 | DROP TABLE owners IF EXISTS; 8 | 9 | 10 | CREATE TABLE vets ( 11 | id INTEGER IDENTITY PRIMARY KEY, 12 | first_name VARCHAR(30), 13 | last_name VARCHAR(30) 14 | ); 15 | CREATE INDEX vets_last_name ON vets (last_name); 16 | 17 | CREATE TABLE specialties ( 18 | id INTEGER IDENTITY PRIMARY KEY, 19 | name VARCHAR(80) 20 | ); 21 | CREATE INDEX specialties_name ON specialties (name); 22 | 23 | CREATE TABLE vet_specialties ( 24 | vet_id INTEGER NOT NULL, 25 | specialty_id INTEGER NOT NULL 26 | ); 27 | ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_vets FOREIGN KEY (vet_id) REFERENCES vets (id); 28 | ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_specialties FOREIGN KEY (specialty_id) REFERENCES specialties (id); 29 | 30 | CREATE TABLE types ( 31 | id INTEGER IDENTITY PRIMARY KEY, 32 | name VARCHAR(80) 33 | ); 34 | CREATE INDEX types_name ON types (name); 35 | 36 | CREATE TABLE owners ( 37 | id INTEGER IDENTITY PRIMARY KEY, 38 | first_name VARCHAR(30), 39 | last_name VARCHAR_IGNORECASE(30), 40 | address VARCHAR(255), 41 | city VARCHAR(80), 42 | telephone VARCHAR(20) 43 | ); 44 | CREATE INDEX owners_last_name ON owners (last_name); 45 | 46 | CREATE TABLE pets ( 47 | id INTEGER IDENTITY PRIMARY KEY, 48 | name VARCHAR(30), 49 | birth_date DATE, 50 | type_id INTEGER NOT NULL, 51 | owner_id INTEGER 52 | ); 53 | ALTER TABLE pets ADD CONSTRAINT fk_pets_owners FOREIGN KEY (owner_id) REFERENCES owners (id); 54 | ALTER TABLE pets ADD CONSTRAINT fk_pets_types FOREIGN KEY (type_id) REFERENCES types (id); 55 | CREATE INDEX pets_name ON pets (name); 56 | 57 | CREATE TABLE visits ( 58 | id INTEGER IDENTITY PRIMARY KEY, 59 | pet_id INTEGER, 60 | visit_date DATE, 61 | description VARCHAR(255) 62 | ); 63 | ALTER TABLE visits ADD CONSTRAINT fk_visits_pets FOREIGN KEY (pet_id) REFERENCES pets (id); 64 | CREATE INDEX visits_pet_id ON visits (pet_id); 65 | -------------------------------------------------------------------------------- /src/main/resources/templates/vets/vetList.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 |

Veterinarians

9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 |
NameSpecialties
none
26 | 27 |
28 | Pages: 29 | [ 30 | 31 | [[${i}]] 32 | [[${i}]] 33 | 34 | 35 | 36 | 38 | 39 | 40 | 41 | 43 | 44 | 45 | 46 | 48 | 49 | 50 | 51 | 53 | 54 | 55 |
56 | 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.system; 18 | 19 | import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; 20 | import org.springframework.cache.annotation.EnableCaching; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Configuration; 23 | 24 | import javax.cache.configuration.MutableConfiguration; 25 | 26 | /** 27 | * Cache configuration intended for caches providing the JCache API. This configuration 28 | * creates the used cache for the application and enables statistics that become 29 | * accessible via JMX. 30 | */ 31 | @Configuration(proxyBeanMethods = false) 32 | @EnableCaching 33 | class CacheConfiguration { 34 | 35 | @Bean 36 | public JCacheManagerCustomizer petclinicCacheConfigurationCustomizer() { 37 | return cm -> cm.createCache("vets", cacheConfiguration()); 38 | } 39 | 40 | /** 41 | * Create a simple configuration that enable statistics via the JCache programmatic 42 | * configuration API. 43 | *

44 | * Within the configuration object that is provided by the JCache API standard, there 45 | * is only a very limited set of configuration options. The really relevant 46 | * configuration options (like the size limit) must be set via a configuration 47 | * mechanism that is provided by the selected JCache implementation. 48 | */ 49 | private javax.cache.configuration.Configuration cacheConfiguration() { 50 | return new MutableConfiguration<>().setStatisticsEnabled(true); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/vet/VetRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import org.springframework.cache.annotation.Cacheable; 19 | import org.springframework.dao.DataAccessException; 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.Pageable; 22 | import org.springframework.data.repository.Repository; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | import java.util.Collection; 26 | 27 | /** 28 | * Repository class for Vet domain objects All method names are compliant 29 | * with Spring Data naming conventions so this interface can easily be extended for Spring 30 | * Data. See: 31 | * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation 32 | * 33 | * @author Ken Krebs 34 | * @author Juergen Hoeller 35 | * @author Sam Brannen 36 | * @author Michael Isvy 37 | */ 38 | public interface VetRepository extends Repository { 39 | 40 | /** 41 | * Retrieve all Vets from the data store. 42 | * @return a Collection of Vets 43 | */ 44 | @Transactional(readOnly = true) 45 | @Cacheable("vets") 46 | Collection findAll() throws DataAccessException; 47 | 48 | /** 49 | * Retrieve all Vets from data store in Pages 50 | * @param pageable 51 | * @return 52 | * @throws DataAccessException 53 | */ 54 | @Transactional(readOnly = true) 55 | @Cacheable("vets") 56 | Page findAll(Pageable pageable) throws DataAccessException; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.format.Formatter; 20 | import org.springframework.stereotype.Component; 21 | 22 | import java.text.ParseException; 23 | import java.util.Collection; 24 | import java.util.Locale; 25 | 26 | /** 27 | * Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting 28 | * from Spring 3.0, Formatters have come as an improvement in comparison to legacy 29 | * PropertyEditors. See the following links for more details: - The Spring ref doc: 30 | * https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#format 31 | * 32 | * @author Mark Fisher 33 | * @author Juergen Hoeller 34 | * @author Michael Isvy 35 | */ 36 | @Component 37 | public class PetTypeFormatter implements Formatter { 38 | 39 | private final OwnerRepository owners; 40 | 41 | @Autowired 42 | public PetTypeFormatter(OwnerRepository owners) { 43 | this.owners = owners; 44 | } 45 | 46 | @Override 47 | public String print(PetType petType, Locale locale) { 48 | return petType.getName(); 49 | } 50 | 51 | @Override 52 | public PetType parse(String text, Locale locale) throws ParseException { 53 | Collection findPetTypes = this.owners.findPetTypes(); 54 | for (PetType type : findPetTypes) { 55 | if (type.getName().equals(text)) { 56 | return type; 57 | } 58 | } 59 | throw new ParseException("type not found: " + text, 0); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/resources/db/h2/schema.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE vet_specialties IF EXISTS; 2 | DROP TABLE vets IF EXISTS; 3 | DROP TABLE specialties IF EXISTS; 4 | DROP TABLE visits IF EXISTS; 5 | DROP TABLE pets IF EXISTS; 6 | DROP TABLE types IF EXISTS; 7 | DROP TABLE owners IF EXISTS; 8 | 9 | 10 | CREATE TABLE vets ( 11 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 12 | first_name VARCHAR(30), 13 | last_name VARCHAR(30) 14 | ); 15 | CREATE INDEX vets_last_name ON vets (last_name); 16 | 17 | CREATE TABLE specialties ( 18 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 19 | name VARCHAR(80) 20 | ); 21 | CREATE INDEX specialties_name ON specialties (name); 22 | 23 | CREATE TABLE vet_specialties ( 24 | vet_id INTEGER NOT NULL, 25 | specialty_id INTEGER NOT NULL 26 | ); 27 | ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_vets FOREIGN KEY (vet_id) REFERENCES vets (id); 28 | ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_specialties FOREIGN KEY (specialty_id) REFERENCES specialties (id); 29 | 30 | CREATE TABLE types ( 31 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 32 | name VARCHAR(80) 33 | ); 34 | CREATE INDEX types_name ON types (name); 35 | 36 | CREATE TABLE owners ( 37 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 38 | first_name VARCHAR(30), 39 | last_name VARCHAR_IGNORECASE(30), 40 | address VARCHAR(255), 41 | city VARCHAR(80), 42 | telephone VARCHAR(20) 43 | ); 44 | CREATE INDEX owners_last_name ON owners (last_name); 45 | 46 | CREATE TABLE pets ( 47 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 48 | name VARCHAR(30), 49 | birth_date DATE, 50 | type_id INTEGER NOT NULL, 51 | owner_id INTEGER 52 | ); 53 | ALTER TABLE pets ADD CONSTRAINT fk_pets_owners FOREIGN KEY (owner_id) REFERENCES owners (id); 54 | ALTER TABLE pets ADD CONSTRAINT fk_pets_types FOREIGN KEY (type_id) REFERENCES types (id); 55 | CREATE INDEX pets_name ON pets (name); 56 | 57 | CREATE TABLE visits ( 58 | id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 59 | pet_id INTEGER, 60 | visit_date DATE, 61 | description VARCHAR(255) 62 | ); 63 | ALTER TABLE visits ADD CONSTRAINT fk_visits_pets FOREIGN KEY (pet_id) REFERENCES pets (id); 64 | CREATE INDEX visits_pet_id ON visits (pet_id); 65 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.model; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | import java.util.Locale; 22 | import java.util.Set; 23 | 24 | import org.junit.jupiter.api.Test; 25 | import org.springframework.context.i18n.LocaleContextHolder; 26 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 27 | 28 | import jakarta.validation.ConstraintViolation; 29 | import jakarta.validation.Validator; 30 | 31 | /** 32 | * @author Michael Isvy Simple test to make sure that Bean Validation is working (useful 33 | * when upgrading to a new version of Hibernate Validator/ Bean Validation) 34 | */ 35 | class ValidatorTests { 36 | 37 | private Validator createValidator() { 38 | LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); 39 | localValidatorFactoryBean.afterPropertiesSet(); 40 | return localValidatorFactoryBean; 41 | } 42 | 43 | @Test 44 | void shouldNotValidateWhenFirstNameEmpty() { 45 | 46 | LocaleContextHolder.setLocale(Locale.ENGLISH); 47 | Person person = new Person(); 48 | person.setFirstName(""); 49 | person.setLastName("smith"); 50 | 51 | Validator validator = createValidator(); 52 | Set> constraintViolations = validator.validate(person); 53 | 54 | assertThat(constraintViolations).hasSize(1); 55 | ConstraintViolation violation = constraintViolations.iterator().next(); 56 | assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); 57 | assertThat(violation.getMessage()).isEqualTo("must not be blank"); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/resources/templates/owners/ownerDetails.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 |

Owner Information

10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
Name
Address
City
Telephone
30 | 31 | Edit 32 | Owner 33 | Add 34 | New Pet 35 | 36 |
37 |
38 |
39 |

Pets and Visits

40 | 41 | 42 | 43 | 44 | 55 | 73 | 74 | 75 |
45 |
46 |
Name
47 |
48 |
Birth Date
49 |
51 |
Type
52 |
53 |
54 |
56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 |
Visit DateDescription
Edit PetAdd Visit
72 |
76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/resources/templates/owners/ownersList.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Owners

8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 24 | 28 | 29 | 30 |
NameAddressCityTelephonePets
22 | 23 | 25 | 26 | 27 |
31 |
32 | Pages: 33 | [ 34 | 35 | [[${i}]] 36 | [[${i}]] 37 | 38 | 39 | 40 | 42 | 43 | 44 | 45 | 47 | 48 | 49 | 50 | 52 | 53 | 54 | 55 | 57 | 58 | 59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/PetClinicIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | import org.junit.jupiter.api.Test; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.boot.SpringApplication; 24 | import org.springframework.boot.test.context.SpringBootTest; 25 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 26 | import org.springframework.boot.test.web.server.LocalServerPort; 27 | import org.springframework.boot.web.client.RestTemplateBuilder; 28 | import org.springframework.http.HttpStatus; 29 | import org.springframework.http.RequestEntity; 30 | import org.springframework.http.ResponseEntity; 31 | import org.springframework.samples.petclinic.vet.VetRepository; 32 | import org.springframework.web.client.RestTemplate; 33 | 34 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 35 | public class PetClinicIntegrationTests { 36 | 37 | @LocalServerPort 38 | int port; 39 | 40 | @Autowired 41 | private VetRepository vets; 42 | 43 | @Autowired 44 | private RestTemplateBuilder builder; 45 | 46 | @Test 47 | void testFindAll() throws Exception { 48 | vets.findAll(); 49 | vets.findAll(); // served from cache 50 | } 51 | 52 | @Test 53 | void testOwnerDetails() { 54 | RestTemplate template = builder.rootUri("http://localhost:" + port).build(); 55 | ResponseEntity result = template.exchange(RequestEntity.get("/owners/1").build(), String.class); 56 | assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); 57 | } 58 | 59 | public static void main(String[] args) { 60 | SpringApplication.run(PetClinicApplication.class, args); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/Pet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.time.LocalDate; 19 | import java.util.Collection; 20 | import java.util.LinkedHashSet; 21 | import java.util.Set; 22 | 23 | import org.springframework.format.annotation.DateTimeFormat; 24 | import org.springframework.samples.petclinic.model.NamedEntity; 25 | 26 | import jakarta.persistence.CascadeType; 27 | import jakarta.persistence.Column; 28 | import jakarta.persistence.Entity; 29 | import jakarta.persistence.FetchType; 30 | import jakarta.persistence.JoinColumn; 31 | import jakarta.persistence.ManyToOne; 32 | import jakarta.persistence.OneToMany; 33 | import jakarta.persistence.OrderBy; 34 | import jakarta.persistence.Table; 35 | 36 | /** 37 | * Simple business object representing a pet. 38 | * 39 | * @author Ken Krebs 40 | * @author Juergen Hoeller 41 | * @author Sam Brannen 42 | */ 43 | @Entity 44 | @Table(name = "pets") 45 | public class Pet extends NamedEntity { 46 | 47 | @Column(name = "birth_date") 48 | @DateTimeFormat(pattern = "yyyy-MM-dd") 49 | private LocalDate birthDate; 50 | 51 | @ManyToOne 52 | @JoinColumn(name = "type_id") 53 | private PetType type; 54 | 55 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 56 | @JoinColumn(name = "pet_id") 57 | @OrderBy("visit_date ASC") 58 | private Set visits = new LinkedHashSet<>(); 59 | 60 | public void setBirthDate(LocalDate birthDate) { 61 | this.birthDate = birthDate; 62 | } 63 | 64 | public LocalDate getBirthDate() { 65 | return this.birthDate; 66 | } 67 | 68 | public PetType getType() { 69 | return this.type; 70 | } 71 | 72 | public void setType(PetType type) { 73 | this.type = type; 74 | } 75 | 76 | public Collection getVisits() { 77 | return this.visits; 78 | } 79 | 80 | public void addVisit(Visit visit) { 81 | getVisits().add(visit); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/vet/Vet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.HashSet; 21 | import java.util.List; 22 | import java.util.Set; 23 | 24 | import org.springframework.beans.support.MutableSortDefinition; 25 | import org.springframework.beans.support.PropertyComparator; 26 | import org.springframework.samples.petclinic.model.Person; 27 | 28 | import jakarta.persistence.Entity; 29 | import jakarta.persistence.FetchType; 30 | import jakarta.persistence.JoinColumn; 31 | import jakarta.persistence.JoinTable; 32 | import jakarta.persistence.ManyToMany; 33 | import jakarta.persistence.Table; 34 | import jakarta.xml.bind.annotation.XmlElement; 35 | 36 | /** 37 | * Simple JavaBean domain object representing a veterinarian. 38 | * 39 | * @author Ken Krebs 40 | * @author Juergen Hoeller 41 | * @author Sam Brannen 42 | * @author Arjen Poutsma 43 | */ 44 | @Entity 45 | @Table(name = "vets") 46 | public class Vet extends Person { 47 | 48 | @ManyToMany(fetch = FetchType.EAGER) 49 | @JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"), 50 | inverseJoinColumns = @JoinColumn(name = "specialty_id")) 51 | private Set specialties; 52 | 53 | protected Set getSpecialtiesInternal() { 54 | if (this.specialties == null) { 55 | this.specialties = new HashSet<>(); 56 | } 57 | return this.specialties; 58 | } 59 | 60 | protected void setSpecialtiesInternal(Set specialties) { 61 | this.specialties = specialties; 62 | } 63 | 64 | @XmlElement 65 | public List getSpecialties() { 66 | List sortedSpecs = new ArrayList<>(getSpecialtiesInternal()); 67 | PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true)); 68 | return Collections.unmodifiableList(sortedSpecs); 69 | } 70 | 71 | public int getNrOfSpecialties() { 72 | return getSpecialtiesInternal().size(); 73 | } 74 | 75 | public void addSpecialty(Specialty specialty) { 76 | getSpecialtiesInternal().add(specialty); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/MySqlIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | import org.junit.jupiter.api.Test; 22 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.context.SpringBootTest; 25 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 26 | import org.springframework.boot.test.web.server.LocalServerPort; 27 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 28 | import org.springframework.boot.web.client.RestTemplateBuilder; 29 | import org.springframework.http.HttpStatus; 30 | import org.springframework.http.RequestEntity; 31 | import org.springframework.http.ResponseEntity; 32 | import org.springframework.samples.petclinic.vet.VetRepository; 33 | import org.springframework.test.context.ActiveProfiles; 34 | import org.springframework.web.client.RestTemplate; 35 | import org.testcontainers.containers.MySQLContainer; 36 | import org.testcontainers.junit.jupiter.Container; 37 | import org.testcontainers.junit.jupiter.Testcontainers; 38 | 39 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 40 | @ActiveProfiles("mysql") 41 | @Testcontainers(disabledWithoutDocker = true) 42 | @DisabledInNativeImage 43 | class MySqlIntegrationTests { 44 | 45 | @ServiceConnection 46 | @Container 47 | static MySQLContainer container = new MySQLContainer<>("mysql:8.2"); 48 | 49 | @LocalServerPort 50 | int port; 51 | 52 | @Autowired 53 | private VetRepository vets; 54 | 55 | @Autowired 56 | private RestTemplateBuilder builder; 57 | 58 | @Test 59 | void testFindAll() throws Exception { 60 | vets.findAll(); 61 | vets.findAll(); // served from cache 62 | } 63 | 64 | @Test 65 | void testOwnerDetails() { 66 | RestTemplate template = builder.rootUri("http://localhost:" + port).build(); 67 | ResponseEntity result = template.exchange(RequestEntity.get("/owners/1").build(), String.class); 68 | assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/vet/VetController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.vet; 17 | 18 | import java.util.List; 19 | 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.PageRequest; 22 | import org.springframework.data.domain.Pageable; 23 | import org.springframework.stereotype.Controller; 24 | import org.springframework.ui.Model; 25 | import org.springframework.web.bind.annotation.GetMapping; 26 | import org.springframework.web.bind.annotation.RequestParam; 27 | import org.springframework.web.bind.annotation.ResponseBody; 28 | 29 | /** 30 | * @author Juergen Hoeller 31 | * @author Mark Fisher 32 | * @author Ken Krebs 33 | * @author Arjen Poutsma 34 | */ 35 | @Controller 36 | class VetController { 37 | 38 | private final VetRepository vetRepository; 39 | 40 | public VetController(VetRepository clinicService) { 41 | this.vetRepository = clinicService; 42 | } 43 | 44 | @GetMapping("/vets.html") 45 | public String showVetList(@RequestParam(defaultValue = "1") int page, Model model) { 46 | // Here we are returning an object of type 'Vets' rather than a collection of Vet 47 | // objects so it is simpler for Object-Xml mapping 48 | Vets vets = new Vets(); 49 | Page paginated = findPaginated(page); 50 | vets.getVetList().addAll(paginated.toList()); 51 | return addPaginationModel(page, paginated, model); 52 | } 53 | 54 | private String addPaginationModel(int page, Page paginated, Model model) { 55 | List listVets = paginated.getContent(); 56 | model.addAttribute("currentPage", page); 57 | model.addAttribute("totalPages", paginated.getTotalPages()); 58 | model.addAttribute("totalItems", paginated.getTotalElements()); 59 | model.addAttribute("listVets", listVets); 60 | return "vets/vetList"; 61 | } 62 | 63 | private Page findPaginated(int page) { 64 | int pageSize = 5; 65 | Pageable pageable = PageRequest.of(page - 1, pageSize); 66 | return vetRepository.findAll(pageable); 67 | } 68 | 69 | @GetMapping({ "/vets" }) 70 | public @ResponseBody Vets showResourcesVetList() { 71 | // Here we are returning an object of type 'Vets' rather than a collection of Vet 72 | // objects so it is simpler for JSon/Object mapping 73 | Vets vets = new Vets(); 74 | vets.getVetList().addAll(this.vetRepository.findAll()); 75 | return vets; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/resources/db/hsqldb/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO vets VALUES (1, 'James', 'Carter'); 2 | INSERT INTO vets VALUES (2, 'Helen', 'Leary'); 3 | INSERT INTO vets VALUES (3, 'Linda', 'Douglas'); 4 | INSERT INTO vets VALUES (4, 'Rafael', 'Ortega'); 5 | INSERT INTO vets VALUES (5, 'Henry', 'Stevens'); 6 | INSERT INTO vets VALUES (6, 'Sharon', 'Jenkins'); 7 | 8 | INSERT INTO specialties VALUES (1, 'radiology'); 9 | INSERT INTO specialties VALUES (2, 'surgery'); 10 | INSERT INTO specialties VALUES (3, 'dentistry'); 11 | 12 | INSERT INTO vet_specialties VALUES (2, 1); 13 | INSERT INTO vet_specialties VALUES (3, 2); 14 | INSERT INTO vet_specialties VALUES (3, 3); 15 | INSERT INTO vet_specialties VALUES (4, 2); 16 | INSERT INTO vet_specialties VALUES (5, 1); 17 | 18 | INSERT INTO types VALUES (1, 'cat'); 19 | INSERT INTO types VALUES (2, 'dog'); 20 | INSERT INTO types VALUES (3, 'lizard'); 21 | INSERT INTO types VALUES (4, 'snake'); 22 | INSERT INTO types VALUES (5, 'bird'); 23 | INSERT INTO types VALUES (6, 'hamster'); 24 | 25 | INSERT INTO owners VALUES (1, 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023'); 26 | INSERT INTO owners VALUES (2, 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749'); 27 | INSERT INTO owners VALUES (3, 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763'); 28 | INSERT INTO owners VALUES (4, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198'); 29 | INSERT INTO owners VALUES (5, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765'); 30 | INSERT INTO owners VALUES (6, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654'); 31 | INSERT INTO owners VALUES (7, 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387'); 32 | INSERT INTO owners VALUES (8, 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683'); 33 | INSERT INTO owners VALUES (9, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435'); 34 | INSERT INTO owners VALUES (10, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487'); 35 | 36 | INSERT INTO pets VALUES (1, 'Leo', '2010-09-07', 1, 1); 37 | INSERT INTO pets VALUES (2, 'Basil', '2012-08-06', 6, 2); 38 | INSERT INTO pets VALUES (3, 'Rosy', '2011-04-17', 2, 3); 39 | INSERT INTO pets VALUES (4, 'Jewel', '2010-03-07', 2, 3); 40 | INSERT INTO pets VALUES (5, 'Iggy', '2010-11-30', 3, 4); 41 | INSERT INTO pets VALUES (6, 'George', '2010-01-20', 4, 5); 42 | INSERT INTO pets VALUES (7, 'Samantha', '2012-09-04', 1, 6); 43 | INSERT INTO pets VALUES (8, 'Max', '2012-09-04', 1, 6); 44 | INSERT INTO pets VALUES (9, 'Lucky', '2011-08-06', 5, 7); 45 | INSERT INTO pets VALUES (10, 'Mulligan', '2007-02-24', 2, 8); 46 | INSERT INTO pets VALUES (11, 'Freddy', '2010-03-09', 5, 9); 47 | INSERT INTO pets VALUES (12, 'Lucky', '2010-06-24', 2, 10); 48 | INSERT INTO pets VALUES (13, 'Sly', '2012-06-08', 1, 10); 49 | 50 | INSERT INTO visits VALUES (1, 7, '2013-01-01', 'rabies shot'); 51 | INSERT INTO visits VALUES (2, 8, '2013-01-02', 'rabies shot'); 52 | INSERT INTO visits VALUES (3, 8, '2013-01-03', 'neutered'); 53 | INSERT INTO visits VALUES (4, 7, '2013-01-04', 'spayed'); 54 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/owner/PetTypeFormatterTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.owner; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.mockito.BDDMockito.given; 21 | 22 | import java.text.ParseException; 23 | import java.util.ArrayList; 24 | import java.util.Collection; 25 | import java.util.List; 26 | import java.util.Locale; 27 | 28 | import org.junit.jupiter.api.Assertions; 29 | import org.junit.jupiter.api.BeforeEach; 30 | import org.junit.jupiter.api.Test; 31 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 32 | import org.junit.jupiter.api.extension.ExtendWith; 33 | import org.mockito.Mock; 34 | import org.mockito.junit.jupiter.MockitoExtension; 35 | 36 | /** 37 | * Test class for {@link PetTypeFormatter} 38 | * 39 | * @author Colin But 40 | */ 41 | @ExtendWith(MockitoExtension.class) 42 | @DisabledInNativeImage 43 | class PetTypeFormatterTests { 44 | 45 | @Mock 46 | private OwnerRepository pets; 47 | 48 | private PetTypeFormatter petTypeFormatter; 49 | 50 | @BeforeEach 51 | void setup() { 52 | this.petTypeFormatter = new PetTypeFormatter(pets); 53 | } 54 | 55 | @Test 56 | void testPrint() { 57 | PetType petType = new PetType(); 58 | petType.setName("Hamster"); 59 | String petTypeName = this.petTypeFormatter.print(petType, Locale.ENGLISH); 60 | assertThat(petTypeName).isEqualTo("Hamster"); 61 | } 62 | 63 | @Test 64 | void shouldParse() throws ParseException { 65 | given(this.pets.findPetTypes()).willReturn(makePetTypes()); 66 | PetType petType = petTypeFormatter.parse("Bird", Locale.ENGLISH); 67 | assertThat(petType.getName()).isEqualTo("Bird"); 68 | } 69 | 70 | @Test 71 | void shouldThrowParseException() throws ParseException { 72 | given(this.pets.findPetTypes()).willReturn(makePetTypes()); 73 | Assertions.assertThrows(ParseException.class, () -> { 74 | petTypeFormatter.parse("Fish", Locale.ENGLISH); 75 | }); 76 | } 77 | 78 | /** 79 | * Helper method to produce some sample pet types just for test purpose 80 | * @return {@link Collection} of {@link PetType} 81 | */ 82 | private List makePetTypes() { 83 | List petTypes = new ArrayList<>(); 84 | petTypes.add(new PetType() { 85 | { 86 | setName("Dog"); 87 | } 88 | }); 89 | petTypes.add(new PetType() { 90 | { 91 | setName("Bird"); 92 | } 93 | }); 94 | return petTypes; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.util.List; 19 | 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.Pageable; 22 | import org.springframework.data.jpa.repository.Query; 23 | import org.springframework.data.repository.Repository; 24 | import org.springframework.data.repository.query.Param; 25 | import org.springframework.transaction.annotation.Transactional; 26 | 27 | /** 28 | * Repository class for Owner domain objects All method names are compliant 29 | * with Spring Data naming conventions so this interface can easily be extended for Spring 30 | * Data. See: 31 | * https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation 32 | * 33 | * @author Ken Krebs 34 | * @author Juergen Hoeller 35 | * @author Sam Brannen 36 | * @author Michael Isvy 37 | */ 38 | public interface OwnerRepository extends Repository { 39 | 40 | /** 41 | * Retrieve all {@link PetType}s from the data store. 42 | * @return a Collection of {@link PetType}s. 43 | */ 44 | @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") 45 | @Transactional(readOnly = true) 46 | List findPetTypes(); 47 | 48 | /** 49 | * Retrieve {@link Owner}s from the data store by last name, returning all owners 50 | * whose last name starts with the given name. 51 | * @param lastName Value to search for 52 | * @return a Collection of matching {@link Owner}s (or an empty Collection if none 53 | * found) 54 | */ 55 | 56 | @Query("SELECT DISTINCT owner FROM Owner owner left join owner.pets WHERE owner.lastName LIKE :lastName% ") 57 | @Transactional(readOnly = true) 58 | Page findByLastName(@Param("lastName") String lastName, Pageable pageable); 59 | 60 | /** 61 | * Retrieve an {@link Owner} from the data store by id. 62 | * @param id the id to search for 63 | * @return the {@link Owner} if found 64 | */ 65 | @Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id") 66 | @Transactional(readOnly = true) 67 | Owner findById(@Param("id") Integer id); 68 | 69 | /** 70 | * Save an {@link Owner} to the data store, either inserting or updating it. 71 | * @param owner the {@link Owner} to save 72 | */ 73 | void save(Owner owner); 74 | 75 | /** 76 | * Returns all the owners from data store 77 | **/ 78 | @Query("SELECT owner FROM Owner owner") 79 | @Transactional(readOnly = true) 80 | Page findAll(Pageable pageable); 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/resources/db/h2/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO vets VALUES (default, 'James', 'Carter'); 2 | INSERT INTO vets VALUES (default, 'Helen', 'Leary'); 3 | INSERT INTO vets VALUES (default, 'Linda', 'Douglas'); 4 | INSERT INTO vets VALUES (default, 'Rafael', 'Ortega'); 5 | INSERT INTO vets VALUES (default, 'Henry', 'Stevens'); 6 | INSERT INTO vets VALUES (default, 'Sharon', 'Jenkins'); 7 | 8 | INSERT INTO specialties VALUES (default, 'radiology'); 9 | INSERT INTO specialties VALUES (default, 'surgery'); 10 | INSERT INTO specialties VALUES (default, 'dentistry'); 11 | 12 | INSERT INTO vet_specialties VALUES (2, 1); 13 | INSERT INTO vet_specialties VALUES (3, 2); 14 | INSERT INTO vet_specialties VALUES (3, 3); 15 | INSERT INTO vet_specialties VALUES (4, 2); 16 | INSERT INTO vet_specialties VALUES (5, 1); 17 | 18 | INSERT INTO types VALUES (default, 'cat'); 19 | INSERT INTO types VALUES (default, 'dog'); 20 | INSERT INTO types VALUES (default, 'lizard'); 21 | INSERT INTO types VALUES (default, 'snake'); 22 | INSERT INTO types VALUES (default, 'bird'); 23 | INSERT INTO types VALUES (default, 'hamster'); 24 | 25 | INSERT INTO owners VALUES (default, 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023'); 26 | INSERT INTO owners VALUES (default, 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749'); 27 | INSERT INTO owners VALUES (default, 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763'); 28 | INSERT INTO owners VALUES (default, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198'); 29 | INSERT INTO owners VALUES (default, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765'); 30 | INSERT INTO owners VALUES (default, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654'); 31 | INSERT INTO owners VALUES (default, 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387'); 32 | INSERT INTO owners VALUES (default, 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683'); 33 | INSERT INTO owners VALUES (default, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435'); 34 | INSERT INTO owners VALUES (default, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487'); 35 | 36 | INSERT INTO pets VALUES (default, 'Leo', '2010-09-07', 1, 1); 37 | INSERT INTO pets VALUES (default, 'Basil', '2012-08-06', 6, 2); 38 | INSERT INTO pets VALUES (default, 'Rosy', '2011-04-17', 2, 3); 39 | INSERT INTO pets VALUES (default, 'Jewel', '2010-03-07', 2, 3); 40 | INSERT INTO pets VALUES (default, 'Iggy', '2010-11-30', 3, 4); 41 | INSERT INTO pets VALUES (default, 'George', '2010-01-20', 4, 5); 42 | INSERT INTO pets VALUES (default, 'Samantha', '2012-09-04', 1, 6); 43 | INSERT INTO pets VALUES (default, 'Max', '2012-09-04', 1, 6); 44 | INSERT INTO pets VALUES (default, 'Lucky', '2011-08-06', 5, 7); 45 | INSERT INTO pets VALUES (default, 'Mulligan', '2007-02-24', 2, 8); 46 | INSERT INTO pets VALUES (default, 'Freddy', '2010-03-09', 5, 9); 47 | INSERT INTO pets VALUES (default, 'Lucky', '2010-06-24', 2, 10); 48 | INSERT INTO pets VALUES (default, 'Sly', '2012-06-08', 1, 10); 49 | 50 | INSERT INTO visits VALUES (default, 7, '2013-01-01', 'rabies shot'); 51 | INSERT INTO visits VALUES (default, 8, '2013-01-02', 'rabies shot'); 52 | INSERT INTO visits VALUES (default, 8, '2013-01-03', 'neutered'); 53 | INSERT INTO visits VALUES (default, 7, '2013-01-04', 'spayed'); 54 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/VisitController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.util.Map; 19 | 20 | import org.springframework.stereotype.Controller; 21 | import org.springframework.validation.BindingResult; 22 | import org.springframework.web.bind.WebDataBinder; 23 | import org.springframework.web.bind.annotation.GetMapping; 24 | import org.springframework.web.bind.annotation.InitBinder; 25 | import org.springframework.web.bind.annotation.ModelAttribute; 26 | import org.springframework.web.bind.annotation.PathVariable; 27 | import org.springframework.web.bind.annotation.PostMapping; 28 | 29 | import jakarta.validation.Valid; 30 | 31 | /** 32 | * @author Juergen Hoeller 33 | * @author Ken Krebs 34 | * @author Arjen Poutsma 35 | * @author Michael Isvy 36 | * @author Dave Syer 37 | */ 38 | @Controller 39 | class VisitController { 40 | 41 | private final OwnerRepository owners; 42 | 43 | public VisitController(OwnerRepository owners) { 44 | this.owners = owners; 45 | } 46 | 47 | @InitBinder 48 | public void setAllowedFields(WebDataBinder dataBinder) { 49 | dataBinder.setDisallowedFields("id"); 50 | } 51 | 52 | /** 53 | * Called before each and every @RequestMapping annotated method. 2 goals: - Make sure 54 | * we always have fresh data - Since we do not use the session scope, make sure that 55 | * Pet object always has an id (Even though id is not part of the form fields) 56 | * @param petId 57 | * @return Pet 58 | */ 59 | @ModelAttribute("visit") 60 | public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId, 61 | Map model) { 62 | Owner owner = this.owners.findById(ownerId); 63 | 64 | Pet pet = owner.getPet(petId); 65 | model.put("pet", pet); 66 | model.put("owner", owner); 67 | 68 | Visit visit = new Visit(); 69 | pet.addVisit(visit); 70 | return visit; 71 | } 72 | 73 | // Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is 74 | // called 75 | @GetMapping("/owners/{ownerId}/pets/{petId}/visits/new") 76 | public String initNewVisitForm() { 77 | return "pets/createOrUpdateVisitForm"; 78 | } 79 | 80 | // Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is 81 | // called 82 | @PostMapping("/owners/{ownerId}/pets/{petId}/visits/new") 83 | public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit, 84 | BindingResult result) { 85 | if (result.hasErrors()) { 86 | return "pets/createOrUpdateVisitForm"; 87 | } 88 | 89 | owner.addVisit(petId, visit); 90 | this.owners.save(owner); 91 | return "redirect:/owners/{ownerId}"; 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/resources/db/mysql/data.sql: -------------------------------------------------------------------------------- 1 | INSERT IGNORE INTO vets VALUES (1, 'James', 'Carter'); 2 | INSERT IGNORE INTO vets VALUES (2, 'Helen', 'Leary'); 3 | INSERT IGNORE INTO vets VALUES (3, 'Linda', 'Douglas'); 4 | INSERT IGNORE INTO vets VALUES (4, 'Rafael', 'Ortega'); 5 | INSERT IGNORE INTO vets VALUES (5, 'Henry', 'Stevens'); 6 | INSERT IGNORE INTO vets VALUES (6, 'Sharon', 'Jenkins'); 7 | 8 | INSERT IGNORE INTO specialties VALUES (1, 'radiology'); 9 | INSERT IGNORE INTO specialties VALUES (2, 'surgery'); 10 | INSERT IGNORE INTO specialties VALUES (3, 'dentistry'); 11 | 12 | INSERT IGNORE INTO vet_specialties VALUES (2, 1); 13 | INSERT IGNORE INTO vet_specialties VALUES (3, 2); 14 | INSERT IGNORE INTO vet_specialties VALUES (3, 3); 15 | INSERT IGNORE INTO vet_specialties VALUES (4, 2); 16 | INSERT IGNORE INTO vet_specialties VALUES (5, 1); 17 | 18 | INSERT IGNORE INTO types VALUES (1, 'cat'); 19 | INSERT IGNORE INTO types VALUES (2, 'dog'); 20 | INSERT IGNORE INTO types VALUES (3, 'lizard'); 21 | INSERT IGNORE INTO types VALUES (4, 'snake'); 22 | INSERT IGNORE INTO types VALUES (5, 'bird'); 23 | INSERT IGNORE INTO types VALUES (6, 'hamster'); 24 | 25 | INSERT IGNORE INTO owners VALUES (1, 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023'); 26 | INSERT IGNORE INTO owners VALUES (2, 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749'); 27 | INSERT IGNORE INTO owners VALUES (3, 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763'); 28 | INSERT IGNORE INTO owners VALUES (4, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198'); 29 | INSERT IGNORE INTO owners VALUES (5, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765'); 30 | INSERT IGNORE INTO owners VALUES (6, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654'); 31 | INSERT IGNORE INTO owners VALUES (7, 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387'); 32 | INSERT IGNORE INTO owners VALUES (8, 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683'); 33 | INSERT IGNORE INTO owners VALUES (9, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435'); 34 | INSERT IGNORE INTO owners VALUES (10, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487'); 35 | 36 | INSERT IGNORE INTO pets VALUES (1, 'Leo', '2000-09-07', 1, 1); 37 | INSERT IGNORE INTO pets VALUES (2, 'Basil', '2002-08-06', 6, 2); 38 | INSERT IGNORE INTO pets VALUES (3, 'Rosy', '2001-04-17', 2, 3); 39 | INSERT IGNORE INTO pets VALUES (4, 'Jewel', '2000-03-07', 2, 3); 40 | INSERT IGNORE INTO pets VALUES (5, 'Iggy', '2000-11-30', 3, 4); 41 | INSERT IGNORE INTO pets VALUES (6, 'George', '2000-01-20', 4, 5); 42 | INSERT IGNORE INTO pets VALUES (7, 'Samantha', '1995-09-04', 1, 6); 43 | INSERT IGNORE INTO pets VALUES (8, 'Max', '1995-09-04', 1, 6); 44 | INSERT IGNORE INTO pets VALUES (9, 'Lucky', '1999-08-06', 5, 7); 45 | INSERT IGNORE INTO pets VALUES (10, 'Mulligan', '1997-02-24', 2, 8); 46 | INSERT IGNORE INTO pets VALUES (11, 'Freddy', '2000-03-09', 5, 9); 47 | INSERT IGNORE INTO pets VALUES (12, 'Lucky', '2000-06-24', 2, 10); 48 | INSERT IGNORE INTO pets VALUES (13, 'Sly', '2002-06-08', 1, 10); 49 | 50 | INSERT IGNORE INTO visits VALUES (1, 7, '2010-03-04', 'rabies shot'); 51 | INSERT IGNORE INTO visits VALUES (2, 8, '2011-03-04', 'rabies shot'); 52 | INSERT IGNORE INTO visits VALUES (3, 8, '2009-06-04', 'neutered'); 53 | INSERT IGNORE INTO visits VALUES (4, 7, '2008-09-04', 'spayed'); 54 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.owner; 18 | 19 | import static org.mockito.BDDMockito.given; 20 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 24 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 25 | 26 | import org.junit.jupiter.api.BeforeEach; 27 | import org.junit.jupiter.api.Test; 28 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 31 | import org.springframework.boot.test.mock.mockito.MockBean; 32 | import org.springframework.test.context.aot.DisabledInAotMode; 33 | import org.springframework.test.web.servlet.MockMvc; 34 | 35 | /** 36 | * Test class for {@link VisitController} 37 | * 38 | * @author Colin But 39 | */ 40 | @WebMvcTest(VisitController.class) 41 | @DisabledInNativeImage 42 | @DisabledInAotMode 43 | class VisitControllerTests { 44 | 45 | private static final int TEST_OWNER_ID = 1; 46 | 47 | private static final int TEST_PET_ID = 1; 48 | 49 | @Autowired 50 | private MockMvc mockMvc; 51 | 52 | @MockBean 53 | private OwnerRepository owners; 54 | 55 | @BeforeEach 56 | void init() { 57 | Owner owner = new Owner(); 58 | Pet pet = new Pet(); 59 | owner.addPet(pet); 60 | pet.setId(TEST_PET_ID); 61 | given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner); 62 | } 63 | 64 | @Test 65 | void testInitNewVisitForm() throws Exception { 66 | mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)) 67 | .andExpect(status().isOk()) 68 | .andExpect(view().name("pets/createOrUpdateVisitForm")); 69 | } 70 | 71 | @Test 72 | void testProcessNewVisitFormSuccess() throws Exception { 73 | mockMvc 74 | .perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID) 75 | .param("name", "George") 76 | .param("description", "Visit Description")) 77 | .andExpect(status().is3xxRedirection()) 78 | .andExpect(view().name("redirect:/owners/{ownerId}")); 79 | } 80 | 81 | @Test 82 | void testProcessNewVisitFormHasErrors() throws Exception { 83 | mockMvc 84 | .perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID).param("name", 85 | "George")) 86 | .andExpect(model().attributeHasErrors("visit")) 87 | .andExpect(status().isOk()) 88 | .andExpect(view().name("pets/createOrUpdateVisitForm")); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/resources/templates/fragments/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | PetClinic :: a Spring Framework demonstration 14 | 15 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 73 |
74 |
75 | 76 | 77 | 78 |
79 |
80 |
81 |
82 |
83 | 84 |
85 |
86 |
87 |
88 |
89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.vet; 18 | 19 | import org.assertj.core.util.Lists; 20 | import org.junit.jupiter.api.BeforeEach; 21 | import org.junit.jupiter.api.Test; 22 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 25 | import org.springframework.boot.test.mock.mockito.MockBean; 26 | import org.springframework.data.domain.PageImpl; 27 | import org.springframework.data.domain.Pageable; 28 | import org.springframework.http.MediaType; 29 | import org.springframework.test.context.aot.DisabledInAotMode; 30 | import org.springframework.test.web.servlet.MockMvc; 31 | import org.springframework.test.web.servlet.ResultActions; 32 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 33 | 34 | import static org.mockito.ArgumentMatchers.any; 35 | import static org.mockito.BDDMockito.given; 36 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 37 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 38 | 39 | /** 40 | * Test class for the {@link VetController} 41 | */ 42 | 43 | @WebMvcTest(VetController.class) 44 | @DisabledInNativeImage 45 | @DisabledInAotMode 46 | class VetControllerTests { 47 | 48 | @Autowired 49 | private MockMvc mockMvc; 50 | 51 | @MockBean 52 | private VetRepository vets; 53 | 54 | private Vet james() { 55 | Vet james = new Vet(); 56 | james.setFirstName("James"); 57 | james.setLastName("Carter"); 58 | james.setId(1); 59 | return james; 60 | } 61 | 62 | private Vet helen() { 63 | Vet helen = new Vet(); 64 | helen.setFirstName("Helen"); 65 | helen.setLastName("Leary"); 66 | helen.setId(2); 67 | Specialty radiology = new Specialty(); 68 | radiology.setId(1); 69 | radiology.setName("radiology"); 70 | helen.addSpecialty(radiology); 71 | return helen; 72 | } 73 | 74 | @BeforeEach 75 | void setup() { 76 | given(this.vets.findAll()).willReturn(Lists.newArrayList(james(), helen())); 77 | given(this.vets.findAll(any(Pageable.class))) 78 | .willReturn(new PageImpl(Lists.newArrayList(james(), helen()))); 79 | 80 | } 81 | 82 | @Test 83 | void testShowVetListHtml() throws Exception { 84 | 85 | mockMvc.perform(MockMvcRequestBuilders.get("/vets.html?page=1")) 86 | .andExpect(status().isOk()) 87 | .andExpect(model().attributeExists("listVets")) 88 | .andExpect(view().name("vets/vetList")); 89 | 90 | } 91 | 92 | @Test 93 | void testShowResourcesVetList() throws Exception { 94 | ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) 95 | .andExpect(status().isOk()); 96 | actions.andExpect(content().contentType(MediaType.APPLICATION_JSON)) 97 | .andExpect(jsonPath("$.vetList[0].id").value(1)); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.system; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 21 | 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import org.junit.jupiter.api.Test; 26 | import org.springframework.beans.factory.annotation.Autowired; 27 | import org.springframework.beans.factory.annotation.Value; 28 | import org.springframework.boot.autoconfigure.SpringBootApplication; 29 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 30 | import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; 31 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 32 | import org.springframework.boot.test.context.SpringBootTest; 33 | import org.springframework.boot.test.web.client.TestRestTemplate; 34 | import org.springframework.core.ParameterizedTypeReference; 35 | import org.springframework.http.HttpEntity; 36 | import org.springframework.http.HttpHeaders; 37 | import org.springframework.http.HttpMethod; 38 | import org.springframework.http.MediaType; 39 | import org.springframework.http.RequestEntity; 40 | import org.springframework.http.ResponseEntity; 41 | 42 | /** 43 | * Integration Test for {@link CrashController}. 44 | * 45 | * @author Alex Lutz 46 | */ 47 | // NOT Waiting https://github.com/spring-projects/spring-boot/issues/5574 48 | @SpringBootTest(webEnvironment = RANDOM_PORT, 49 | properties = { "server.error.include-message=ALWAYS", "management.endpoints.enabled-by-default=false" }) 50 | class CrashControllerIntegrationTests { 51 | 52 | @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, 53 | DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) 54 | static class TestConfiguration { 55 | 56 | } 57 | 58 | @Value(value = "${local.server.port}") 59 | private int port; 60 | 61 | @Autowired 62 | private TestRestTemplate rest; 63 | 64 | @Test 65 | void testTriggerExceptionJson() { 66 | ResponseEntity> resp = rest.exchange( 67 | RequestEntity.get("http://localhost:" + port + "/oups").build(), 68 | new ParameterizedTypeReference>() { 69 | }); 70 | assertThat(resp).isNotNull(); 71 | assertThat(resp.getStatusCode().is5xxServerError()); 72 | assertThat(resp.getBody().containsKey("timestamp")); 73 | assertThat(resp.getBody().containsKey("status")); 74 | assertThat(resp.getBody().containsKey("error")); 75 | assertThat(resp.getBody()).containsEntry("message", 76 | "Expected: controller used to showcase what happens when an exception is thrown"); 77 | assertThat(resp.getBody()).containsEntry("path", "/oups"); 78 | } 79 | 80 | @Test 81 | void testTriggerExceptionHtml() { 82 | HttpHeaders headers = new HttpHeaders(); 83 | headers.setAccept(List.of(MediaType.TEXT_HTML)); 84 | ResponseEntity resp = rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET, 85 | new HttpEntity<>(headers), String.class); 86 | assertThat(resp).isNotNull(); 87 | assertThat(resp.getStatusCode().is5xxServerError()); 88 | assertThat(resp.getBody()).isNotNull(); 89 | // html: 90 | assertThat(resp.getBody()).containsSubsequence("", "

", "Something happened...", "

", "

", 91 | "Expected:", "controller", "used", "to", "showcase", "what", "happens", "when", "an", "exception", "is", 92 | "thrown", "

", ""); 93 | // Not the whitelabel error page: 94 | assertThat(resp.getBody()).doesNotContain("Whitelabel Error Page", 95 | "This application has no explicit mapping for"); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/Owner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | import org.springframework.core.style.ToStringCreator; 22 | import org.springframework.samples.petclinic.model.Person; 23 | import org.springframework.util.Assert; 24 | 25 | import jakarta.persistence.CascadeType; 26 | import jakarta.persistence.Column; 27 | import jakarta.persistence.Entity; 28 | import jakarta.persistence.FetchType; 29 | import jakarta.persistence.JoinColumn; 30 | import jakarta.persistence.OneToMany; 31 | import jakarta.persistence.OrderBy; 32 | import jakarta.persistence.Table; 33 | import jakarta.validation.constraints.Digits; 34 | import jakarta.validation.constraints.NotBlank; 35 | 36 | /** 37 | * Simple JavaBean domain object representing an owner. 38 | * 39 | * @author Ken Krebs 40 | * @author Juergen Hoeller 41 | * @author Sam Brannen 42 | * @author Michael Isvy 43 | * @author Oliver Drotbohm 44 | */ 45 | @Entity 46 | @Table(name = "owners") 47 | public class Owner extends Person { 48 | 49 | @Column(name = "address") 50 | @NotBlank 51 | private String address; 52 | 53 | @Column(name = "city") 54 | @NotBlank 55 | private String city; 56 | 57 | @Column(name = "telephone") 58 | @NotBlank 59 | @Digits(fraction = 0, integer = 10) 60 | private String telephone; 61 | 62 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 63 | @JoinColumn(name = "owner_id") 64 | @OrderBy("name") 65 | private List pets = new ArrayList<>(); 66 | 67 | public String getAddress() { 68 | return this.address; 69 | } 70 | 71 | public void setAddress(String address) { 72 | this.address = address; 73 | } 74 | 75 | public String getCity() { 76 | return this.city; 77 | } 78 | 79 | public void setCity(String city) { 80 | this.city = city; 81 | } 82 | 83 | public String getTelephone() { 84 | return this.telephone; 85 | } 86 | 87 | public void setTelephone(String telephone) { 88 | this.telephone = telephone; 89 | } 90 | 91 | public List getPets() { 92 | return this.pets; 93 | } 94 | 95 | public void addPet(Pet pet) { 96 | if (pet.isNew()) { 97 | getPets().add(pet); 98 | } 99 | } 100 | 101 | /** 102 | * Return the Pet with the given name, or null if none found for this Owner. 103 | * @param name to test 104 | * @return a pet if pet name is already in use 105 | */ 106 | public Pet getPet(String name) { 107 | return getPet(name, false); 108 | } 109 | 110 | /** 111 | * Return the Pet with the given id, or null if none found for this Owner. 112 | * @param id to test 113 | * @return a pet if pet id is already in use 114 | */ 115 | public Pet getPet(Integer id) { 116 | for (Pet pet : getPets()) { 117 | if (!pet.isNew()) { 118 | Integer compId = pet.getId(); 119 | if (compId.equals(id)) { 120 | return pet; 121 | } 122 | } 123 | } 124 | return null; 125 | } 126 | 127 | /** 128 | * Return the Pet with the given name, or null if none found for this Owner. 129 | * @param name to test 130 | * @return a pet if pet name is already in use 131 | */ 132 | public Pet getPet(String name, boolean ignoreNew) { 133 | name = name.toLowerCase(); 134 | for (Pet pet : getPets()) { 135 | String compName = pet.getName(); 136 | if (compName != null && compName.equalsIgnoreCase(name)) { 137 | if (!ignoreNew || !pet.isNew()) { 138 | return pet; 139 | } 140 | } 141 | } 142 | return null; 143 | } 144 | 145 | @Override 146 | public String toString() { 147 | return new ToStringCreator(this).append("id", this.getId()) 148 | .append("new", this.isNew()) 149 | .append("lastName", this.getLastName()) 150 | .append("firstName", this.getFirstName()) 151 | .append("address", this.address) 152 | .append("city", this.city) 153 | .append("telephone", this.telephone) 154 | .toString(); 155 | } 156 | 157 | /** 158 | * Adds the given {@link Visit} to the {@link Pet} with the given identifier. 159 | * @param petId the identifier of the {@link Pet}, must not be {@literal null}. 160 | * @param visit the visit to add, must not be {@literal null}. 161 | */ 162 | public void addVisit(Integer petId, Visit visit) { 163 | 164 | Assert.notNull(petId, "Pet identifier must not be null!"); 165 | Assert.notNull(visit, "Visit must not be null!"); 166 | 167 | Pet pet = getPet(petId); 168 | 169 | Assert.notNull(pet, "Invalid Pet identifier!"); 170 | 171 | pet.addVisit(visit); 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.owner; 18 | 19 | import org.assertj.core.util.Lists; 20 | import org.junit.jupiter.api.BeforeEach; 21 | import org.junit.jupiter.api.Test; 22 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 25 | import org.springframework.boot.test.mock.mockito.MockBean; 26 | import org.springframework.context.annotation.ComponentScan; 27 | import org.springframework.context.annotation.FilterType; 28 | import org.springframework.test.context.aot.DisabledInAotMode; 29 | import org.springframework.test.web.servlet.MockMvc; 30 | 31 | import static org.mockito.BDDMockito.given; 32 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 33 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 34 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 35 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 36 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 37 | 38 | /** 39 | * Test class for the {@link PetController} 40 | * 41 | * @author Colin But 42 | */ 43 | @WebMvcTest(value = PetController.class, 44 | includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) 45 | @DisabledInNativeImage 46 | @DisabledInAotMode 47 | class PetControllerTests { 48 | 49 | private static final int TEST_OWNER_ID = 1; 50 | 51 | private static final int TEST_PET_ID = 1; 52 | 53 | @Autowired 54 | private MockMvc mockMvc; 55 | 56 | @MockBean 57 | private OwnerRepository owners; 58 | 59 | @BeforeEach 60 | void setup() { 61 | PetType cat = new PetType(); 62 | cat.setId(3); 63 | cat.setName("hamster"); 64 | given(this.owners.findPetTypes()).willReturn(Lists.newArrayList(cat)); 65 | Owner owner = new Owner(); 66 | Pet pet = new Pet(); 67 | owner.addPet(pet); 68 | pet.setId(TEST_PET_ID); 69 | given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner); 70 | } 71 | 72 | @Test 73 | void testInitCreationForm() throws Exception { 74 | mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)) 75 | .andExpect(status().isOk()) 76 | .andExpect(view().name("pets/createOrUpdatePetForm")) 77 | .andExpect(model().attributeExists("pet")); 78 | } 79 | 80 | @Test 81 | void testProcessCreationFormSuccess() throws Exception { 82 | mockMvc 83 | .perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") 84 | .param("type", "hamster") 85 | .param("birthDate", "2015-02-12")) 86 | .andExpect(status().is3xxRedirection()) 87 | .andExpect(view().name("redirect:/owners/{ownerId}")); 88 | } 89 | 90 | @Test 91 | void testProcessCreationFormHasErrors() throws Exception { 92 | mockMvc 93 | .perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") 94 | .param("birthDate", "2015-02-12")) 95 | .andExpect(model().attributeHasNoErrors("owner")) 96 | .andExpect(model().attributeHasErrors("pet")) 97 | .andExpect(model().attributeHasFieldErrors("pet", "type")) 98 | .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")) 99 | .andExpect(status().isOk()) 100 | .andExpect(view().name("pets/createOrUpdatePetForm")); 101 | } 102 | 103 | @Test 104 | void testInitUpdateForm() throws Exception { 105 | mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID)) 106 | .andExpect(status().isOk()) 107 | .andExpect(model().attributeExists("pet")) 108 | .andExpect(view().name("pets/createOrUpdatePetForm")); 109 | } 110 | 111 | @Test 112 | void testProcessUpdateFormSuccess() throws Exception { 113 | mockMvc 114 | .perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") 115 | .param("type", "hamster") 116 | .param("birthDate", "2015-02-12")) 117 | .andExpect(status().is3xxRedirection()) 118 | .andExpect(view().name("redirect:/owners/{ownerId}")); 119 | } 120 | 121 | @Test 122 | void testProcessUpdateFormHasErrors() throws Exception { 123 | mockMvc 124 | .perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") 125 | .param("birthDate", "2015/02/12")) 126 | .andExpect(model().attributeHasNoErrors("owner")) 127 | .andExpect(model().attributeHasErrors("pet")) 128 | .andExpect(status().isOk()) 129 | .andExpect(view().name("pets/createOrUpdatePetForm")); 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/PostgresIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.junit.jupiter.api.Assumptions.assumeTrue; 21 | 22 | import java.util.Arrays; 23 | import java.util.LinkedList; 24 | import java.util.List; 25 | 26 | import org.apache.commons.logging.Log; 27 | import org.apache.commons.logging.LogFactory; 28 | import org.junit.jupiter.api.BeforeAll; 29 | import org.junit.jupiter.api.Test; 30 | import org.junit.jupiter.api.condition.DisabledInNativeImage; 31 | import org.springframework.beans.factory.annotation.Autowired; 32 | import org.springframework.boot.builder.SpringApplicationBuilder; 33 | import org.springframework.boot.context.event.ApplicationPreparedEvent; 34 | import org.springframework.boot.test.context.SpringBootTest; 35 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 36 | import org.springframework.boot.test.web.server.LocalServerPort; 37 | import org.springframework.boot.web.client.RestTemplateBuilder; 38 | import org.springframework.context.ApplicationListener; 39 | import org.springframework.core.env.ConfigurableEnvironment; 40 | import org.springframework.core.env.EnumerablePropertySource; 41 | import org.springframework.core.env.PropertySource; 42 | import org.springframework.http.HttpStatus; 43 | import org.springframework.http.RequestEntity; 44 | import org.springframework.http.ResponseEntity; 45 | import org.springframework.samples.petclinic.vet.VetRepository; 46 | import org.springframework.test.context.ActiveProfiles; 47 | import org.springframework.web.client.RestTemplate; 48 | import org.testcontainers.DockerClientFactory; 49 | 50 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.docker.compose.skip.in-tests=false", // 51 | "spring.docker.compose.profiles.active=postgres" }) 52 | @ActiveProfiles("postgres") 53 | @DisabledInNativeImage 54 | public class PostgresIntegrationTests { 55 | 56 | @LocalServerPort 57 | int port; 58 | 59 | @Autowired 60 | private VetRepository vets; 61 | 62 | @Autowired 63 | private RestTemplateBuilder builder; 64 | 65 | @BeforeAll 66 | static void available() { 67 | assumeTrue(DockerClientFactory.instance().isDockerAvailable(), "Docker not available"); 68 | } 69 | 70 | public static void main(String[] args) { 71 | new SpringApplicationBuilder(PetClinicApplication.class) // 72 | .profiles("postgres") // 73 | .properties( // 74 | "spring.docker.compose.profiles.active=postgres" // 75 | ) // 76 | .listeners(new PropertiesLogger()) // 77 | .run(args); 78 | } 79 | 80 | @Test 81 | void testFindAll() throws Exception { 82 | vets.findAll(); 83 | vets.findAll(); // served from cache 84 | } 85 | 86 | @Test 87 | void testOwnerDetails() { 88 | RestTemplate template = builder.rootUri("http://localhost:" + port).build(); 89 | ResponseEntity result = template.exchange(RequestEntity.get("/owners/1").build(), String.class); 90 | assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); 91 | } 92 | 93 | static class PropertiesLogger implements ApplicationListener { 94 | 95 | private static final Log log = LogFactory.getLog(PropertiesLogger.class); 96 | 97 | private ConfigurableEnvironment environment; 98 | 99 | private boolean isFirstRun = true; 100 | 101 | @Override 102 | public void onApplicationEvent(ApplicationPreparedEvent event) { 103 | if (isFirstRun) { 104 | environment = event.getApplicationContext().getEnvironment(); 105 | printProperties(); 106 | } 107 | isFirstRun = false; 108 | } 109 | 110 | public void printProperties() { 111 | for (EnumerablePropertySource source : findPropertiesPropertySources()) { 112 | log.info("PropertySource: " + source.getName()); 113 | String[] names = source.getPropertyNames(); 114 | Arrays.sort(names); 115 | for (String name : names) { 116 | String resolved = environment.getProperty(name); 117 | String value = source.getProperty(name).toString(); 118 | if (resolved.equals(value)) { 119 | log.info(name + "=" + resolved); 120 | } 121 | else { 122 | log.info(name + "=" + value + " OVERRIDDEN to " + resolved); 123 | } 124 | } 125 | } 126 | } 127 | 128 | private List> findPropertiesPropertySources() { 129 | List> sources = new LinkedList<>(); 130 | for (PropertySource source : environment.getPropertySources()) { 131 | if (source instanceof EnumerablePropertySource enumerable) { 132 | sources.add(enumerable); 133 | } 134 | } 135 | return sources; 136 | } 137 | 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0' 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/PetController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.time.LocalDate; 19 | import java.util.Collection; 20 | 21 | import org.springframework.stereotype.Controller; 22 | import org.springframework.ui.ModelMap; 23 | import org.springframework.util.StringUtils; 24 | import org.springframework.validation.BindingResult; 25 | import org.springframework.web.bind.WebDataBinder; 26 | import org.springframework.web.bind.annotation.GetMapping; 27 | import org.springframework.web.bind.annotation.InitBinder; 28 | import org.springframework.web.bind.annotation.ModelAttribute; 29 | import org.springframework.web.bind.annotation.PathVariable; 30 | import org.springframework.web.bind.annotation.PostMapping; 31 | import org.springframework.web.bind.annotation.RequestMapping; 32 | 33 | import jakarta.validation.Valid; 34 | 35 | /** 36 | * @author Juergen Hoeller 37 | * @author Ken Krebs 38 | * @author Arjen Poutsma 39 | */ 40 | @Controller 41 | @RequestMapping("/owners/{ownerId}") 42 | class PetController { 43 | 44 | private static final String VIEWS_PETS_CREATE_OR_UPDATE_FORM = "pets/createOrUpdatePetForm"; 45 | 46 | private final OwnerRepository owners; 47 | 48 | public PetController(OwnerRepository owners) { 49 | this.owners = owners; 50 | } 51 | 52 | @ModelAttribute("types") 53 | public Collection populatePetTypes() { 54 | return this.owners.findPetTypes(); 55 | } 56 | 57 | @ModelAttribute("owner") 58 | public Owner findOwner(@PathVariable("ownerId") int ownerId) { 59 | 60 | Owner owner = this.owners.findById(ownerId); 61 | if (owner == null) { 62 | throw new IllegalArgumentException("Owner ID not found: " + ownerId); 63 | } 64 | return owner; 65 | } 66 | 67 | @ModelAttribute("pet") 68 | public Pet findPet(@PathVariable("ownerId") int ownerId, 69 | @PathVariable(name = "petId", required = false) Integer petId) { 70 | 71 | Owner owner = this.owners.findById(ownerId); 72 | if (owner == null) { 73 | throw new IllegalArgumentException("Owner ID not found: " + ownerId); 74 | } 75 | return petId == null ? new Pet() : owner.getPet(petId); 76 | } 77 | 78 | @InitBinder("owner") 79 | public void initOwnerBinder(WebDataBinder dataBinder) { 80 | dataBinder.setDisallowedFields("id"); 81 | } 82 | 83 | @InitBinder("pet") 84 | public void initPetBinder(WebDataBinder dataBinder) { 85 | dataBinder.setValidator(new PetValidator()); 86 | } 87 | 88 | @GetMapping("/pets/new") 89 | public String initCreationForm(Owner owner, ModelMap model) { 90 | Pet pet = new Pet(); 91 | owner.addPet(pet); 92 | model.put("pet", pet); 93 | return VIEWS_PETS_CREATE_OR_UPDATE_FORM; 94 | } 95 | 96 | @PostMapping("/pets/new") 97 | public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) { 98 | if (StringUtils.hasText(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null) { 99 | result.rejectValue("name", "duplicate", "already exists"); 100 | } 101 | 102 | LocalDate currentDate = LocalDate.now(); 103 | if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) { 104 | result.rejectValue("birthDate", "typeMismatch.birthDate"); 105 | } 106 | 107 | owner.addPet(pet); 108 | if (result.hasErrors()) { 109 | model.put("pet", pet); 110 | return VIEWS_PETS_CREATE_OR_UPDATE_FORM; 111 | } 112 | 113 | this.owners.save(owner); 114 | return "redirect:/owners/{ownerId}"; 115 | } 116 | 117 | @GetMapping("/pets/{petId}/edit") 118 | public String initUpdateForm(Owner owner, @PathVariable("petId") int petId, ModelMap model) { 119 | Pet pet = owner.getPet(petId); 120 | model.put("pet", pet); 121 | return VIEWS_PETS_CREATE_OR_UPDATE_FORM; 122 | } 123 | 124 | @PostMapping("/pets/{petId}/edit") 125 | public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) { 126 | 127 | String petName = pet.getName(); 128 | 129 | // checking if the pet name already exist for the owner 130 | if (StringUtils.hasText(petName)) { 131 | Pet existingPet = owner.getPet(petName.toLowerCase(), false); 132 | if (existingPet != null && existingPet.getId() != pet.getId()) { 133 | result.rejectValue("name", "duplicate", "already exists"); 134 | } 135 | } 136 | 137 | LocalDate currentDate = LocalDate.now(); 138 | if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) { 139 | result.rejectValue("birthDate", "typeMismatch.birthDate"); 140 | } 141 | 142 | if (result.hasErrors()) { 143 | model.put("pet", pet); 144 | return VIEWS_PETS_CREATE_OR_UPDATE_FORM; 145 | } 146 | 147 | owner.addPet(pet); 148 | this.owners.save(owner); 149 | return "redirect:/owners/{ownerId}"; 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/main/scss/petclinic.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 the original author or authors. 3 | * 4 | * You may obtain a copy of the License at 5 | * 6 | * https://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | @import "bootstrap"; 15 | 16 | $icon-font-path: "../../webjars/bootstrap/fonts/"; 17 | 18 | $spring-green: #6db33f; 19 | $spring-dark-green: #5fa134; 20 | $spring-brown: #34302D; 21 | $spring-grey: #838789; 22 | $spring-light-grey: #f1f1f1; 23 | 24 | $body-bg: $spring-light-grey; 25 | $text-color: $spring-brown; 26 | $link-color: $spring-dark-green; 27 | $link-hover-color: $spring-dark-green; 28 | 29 | $navbar-default-link-color: $spring-light-grey; 30 | $navbar-default-link-active-color: $spring-light-grey; 31 | $navbar-default-link-hover-color: $spring-light-grey; 32 | $navbar-default-link-hover-bg: $spring-green; 33 | $navbar-default-toggle-icon-bar-bg: $spring-light-grey; 34 | $navbar-default-toggle-hover-bg: transparent; 35 | $navbar-default-link-active-bg: $spring-green; 36 | 37 | $border-radius-base: 0; 38 | $border-radius-large: 0; 39 | $border-radius-small: 0; 40 | 41 | $nav-tabs-active-link-hover-color: $spring-light-grey; 42 | $nav-tabs-active-link-hover-bg: $spring-brown; 43 | $nav-tabs-active-link-hover-border-color: $spring-brown; 44 | $nav-tabs-border-color: $spring-brown; 45 | 46 | $pagination-active-bg: $spring-brown; 47 | $pagination-active-border: $spring-green; 48 | $table-border-color: $spring-brown; 49 | 50 | .table > thead > tr > th { 51 | background-color: lighten($spring-brown, 3%); 52 | color: $spring-light-grey; 53 | } 54 | 55 | .table-filter { 56 | background-color: $spring-brown; 57 | padding: 9px 12px; 58 | } 59 | 60 | .nav > li > a { 61 | color: $spring-grey; 62 | } 63 | 64 | .btn-primary { 65 | margin-top: 12px; 66 | border-width: 2px; 67 | transition: border 0.15s; 68 | color: $spring-light-grey; 69 | background: $spring-brown; 70 | border-color: $spring-green; 71 | -webkit-transition: border 0.15s; 72 | -moz-transition: border 0.15s; 73 | -o-transition: border 0.15s; 74 | -ms-transition: border 0.15s; 75 | 76 | &:hover, 77 | &:focus, 78 | &:active, 79 | &.active, 80 | .open .dropdown-toggle { 81 | background-color: $spring-brown; 82 | border-color: $spring-brown; 83 | } 84 | } 85 | 86 | 87 | .container .text-muted { 88 | margin: 20px 0; 89 | } 90 | 91 | code { 92 | font-size: 80%; 93 | } 94 | 95 | .xd-container { 96 | margin-top: 40px; 97 | margin-bottom: 100px; 98 | padding-left: 5px; 99 | padding-right: 5px; 100 | } 101 | 102 | h1 { 103 | margin-bottom: 15px 104 | } 105 | 106 | .index-page--subtitle { 107 | font-size: 16px; 108 | line-height: 24px; 109 | margin: 0 0 30px; 110 | } 111 | 112 | .form-horizontal button.btn-inverse { 113 | margin-left: 32px; 114 | } 115 | 116 | #job-params-modal .modal-dialog { 117 | width: 90%; 118 | margin-left:auto; 119 | margin-right:auto; 120 | } 121 | 122 | [ng-cloak].splash { 123 | display: block !important; 124 | } 125 | [ng-cloak] { 126 | display: none; 127 | } 128 | 129 | .splash { 130 | background: $spring-green; 131 | color: $spring-brown; 132 | display: none; 133 | } 134 | 135 | .error-page { 136 | margin-top: 100px; 137 | text-align: center; 138 | } 139 | 140 | .error-page .error-title { 141 | font-size: 24px; 142 | line-height: 24px; 143 | margin: 30px 0 0; 144 | } 145 | 146 | table td { 147 | vertical-align: middle; 148 | } 149 | 150 | table td .progress { 151 | margin-bottom: 0; 152 | } 153 | 154 | table td.action-column { 155 | width: 1px; 156 | } 157 | 158 | .help-block { 159 | color: lighten($text-color, 50%); // lighten the text some for contrast 160 | } 161 | 162 | .xd-containers { 163 | font-size: 15px; 164 | } 165 | 166 | .cluster-view > table td { 167 | vertical-align: top; 168 | } 169 | 170 | .cluster-view .label, .cluster-view .column-block { 171 | display: block; 172 | } 173 | 174 | .cluster-view .input-group-addon { 175 | width: 0%; 176 | } 177 | 178 | .cluster-view { 179 | margin-bottom: 0; 180 | } 181 | 182 | .container-details-table th { 183 | background-color: lighten($spring-brown, 3%); 184 | color: $spring-light-grey; 185 | } 186 | 187 | .status-help-content-table td { 188 | color: $spring-brown; 189 | } 190 | 191 | .logo { 192 | width: 200px; 193 | } 194 | 195 | .myspinner { 196 | animation-name: spinner; 197 | animation-duration: 2s; 198 | animation-iteration-count: infinite; 199 | animation-timing-function: linear; 200 | 201 | -webkit-transform-origin: 49% 50%; 202 | -webkit-animation-name: spinner; 203 | -webkit-animation-duration: 2s; 204 | -webkit-animation-iteration-count: infinite; 205 | -webkit-animation-timing-function: linear; 206 | } 207 | 208 | hr { 209 | border-top: 1px dotted $spring-brown; 210 | } 211 | 212 | @import "typography.scss"; 213 | @import "header.scss"; 214 | @import "responsive.scss"; 215 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.samples.petclinic.owner; 17 | 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | import org.springframework.data.domain.Page; 22 | import org.springframework.data.domain.PageRequest; 23 | import org.springframework.data.domain.Pageable; 24 | import org.springframework.stereotype.Controller; 25 | import org.springframework.ui.Model; 26 | import org.springframework.validation.BindingResult; 27 | import org.springframework.web.bind.WebDataBinder; 28 | import org.springframework.web.bind.annotation.GetMapping; 29 | import org.springframework.web.bind.annotation.InitBinder; 30 | import org.springframework.web.bind.annotation.ModelAttribute; 31 | import org.springframework.web.bind.annotation.PathVariable; 32 | import org.springframework.web.bind.annotation.PostMapping; 33 | import org.springframework.web.bind.annotation.RequestParam; 34 | import org.springframework.web.servlet.ModelAndView; 35 | 36 | import jakarta.validation.Valid; 37 | 38 | /** 39 | * @author Juergen Hoeller 40 | * @author Ken Krebs 41 | * @author Arjen Poutsma 42 | * @author Michael Isvy 43 | */ 44 | @Controller 45 | class OwnerController { 46 | 47 | private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm"; 48 | 49 | private final OwnerRepository owners; 50 | 51 | public OwnerController(OwnerRepository clinicService) { 52 | this.owners = clinicService; 53 | } 54 | 55 | @InitBinder 56 | public void setAllowedFields(WebDataBinder dataBinder) { 57 | dataBinder.setDisallowedFields("id"); 58 | } 59 | 60 | @ModelAttribute("owner") 61 | public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) { 62 | return ownerId == null ? new Owner() : this.owners.findById(ownerId); 63 | } 64 | 65 | @GetMapping("/owners/new") 66 | public String initCreationForm(Map model) { 67 | Owner owner = new Owner(); 68 | model.put("owner", owner); 69 | return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; 70 | } 71 | 72 | @PostMapping("/owners/new") 73 | public String processCreationForm(@Valid Owner owner, BindingResult result) { 74 | if (result.hasErrors()) { 75 | return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; 76 | } 77 | 78 | this.owners.save(owner); 79 | return "redirect:/owners/" + owner.getId(); 80 | } 81 | 82 | @GetMapping("/owners/find") 83 | public String initFindForm() { 84 | return "owners/findOwners"; 85 | } 86 | 87 | @GetMapping("/owners") 88 | public String processFindForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result, 89 | Model model) { 90 | // allow parameterless GET request for /owners to return all records 91 | if (owner.getLastName() == null) { 92 | owner.setLastName(""); // empty string signifies broadest possible search 93 | } 94 | 95 | // find owners by last name 96 | Page ownersResults = findPaginatedForOwnersLastName(page, owner.getLastName()); 97 | if (ownersResults.isEmpty()) { 98 | // no owners found 99 | result.rejectValue("lastName", "notFound", "not found"); 100 | return "owners/findOwners"; 101 | } 102 | 103 | if (ownersResults.getTotalElements() == 1) { 104 | // 1 owner found 105 | owner = ownersResults.iterator().next(); 106 | return "redirect:/owners/" + owner.getId(); 107 | } 108 | 109 | // multiple owners found 110 | return addPaginationModel(page, model, ownersResults); 111 | } 112 | 113 | private String addPaginationModel(int page, Model model, Page paginated) { 114 | List listOwners = paginated.getContent(); 115 | model.addAttribute("currentPage", page); 116 | model.addAttribute("totalPages", paginated.getTotalPages()); 117 | model.addAttribute("totalItems", paginated.getTotalElements()); 118 | model.addAttribute("listOwners", listOwners); 119 | return "owners/ownersList"; 120 | } 121 | 122 | private Page findPaginatedForOwnersLastName(int page, String lastname) { 123 | int pageSize = 5; 124 | Pageable pageable = PageRequest.of(page - 1, pageSize); 125 | return owners.findByLastName(lastname, pageable); 126 | } 127 | 128 | @GetMapping("/owners/{ownerId}/edit") 129 | public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { 130 | Owner owner = this.owners.findById(ownerId); 131 | model.addAttribute(owner); 132 | return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; 133 | } 134 | 135 | @PostMapping("/owners/{ownerId}/edit") 136 | public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, 137 | @PathVariable("ownerId") int ownerId) { 138 | if (result.hasErrors()) { 139 | return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; 140 | } 141 | 142 | owner.setId(ownerId); 143 | this.owners.save(owner); 144 | return "redirect:/owners/{ownerId}"; 145 | } 146 | 147 | /** 148 | * Custom handler for displaying an owner. 149 | * @param ownerId the ID of the owner to display 150 | * @return a ModelMap with the model attributes for the view 151 | */ 152 | @GetMapping("/owners/{ownerId}") 153 | public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { 154 | ModelAndView mav = new ModelAndView("owners/ownerDetails"); 155 | Owner owner = this.owners.findById(ownerId); 156 | mav.addObject(owner); 157 | return mav; 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /src/main/resources/db/postgres/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO vets (first_name, last_name) SELECT 'James', 'Carter' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=1); 2 | INSERT INTO vets (first_name, last_name) SELECT 'Helen', 'Leary' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=2); 3 | INSERT INTO vets (first_name, last_name) SELECT 'Linda', 'Douglas' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=3); 4 | INSERT INTO vets (first_name, last_name) SELECT 'Rafael', 'Ortega' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=4); 5 | INSERT INTO vets (first_name, last_name) SELECT 'Henry', 'Stevens' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=5); 6 | INSERT INTO vets (first_name, last_name) SELECT 'Sharon', 'Jenkins' WHERE NOT EXISTS (SELECT * FROM vets WHERE id=6); 7 | 8 | INSERT INTO specialties (name) SELECT 'radiology' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='radiology'); 9 | INSERT INTO specialties (name) SELECT 'surgery' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='surgery'); 10 | INSERT INTO specialties (name) SELECT 'dentistry' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='dentistry'); 11 | 12 | INSERT INTO vet_specialties VALUES (2, 1) ON CONFLICT (vet_id, specialty_id) DO NOTHING; 13 | INSERT INTO vet_specialties VALUES (3, 2) ON CONFLICT (vet_id, specialty_id) DO NOTHING; 14 | INSERT INTO vet_specialties VALUES (3, 3) ON CONFLICT (vet_id, specialty_id) DO NOTHING; 15 | INSERT INTO vet_specialties VALUES (4, 2) ON CONFLICT (vet_id, specialty_id) DO NOTHING; 16 | INSERT INTO vet_specialties VALUES (5, 1) ON CONFLICT (vet_id, specialty_id) DO NOTHING; 17 | 18 | INSERT INTO types (name) SELECT 'cat' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='cat'); 19 | INSERT INTO types (name) SELECT 'dog' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='dog'); 20 | INSERT INTO types (name) SELECT 'lizard' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='lizard'); 21 | INSERT INTO types (name) SELECT 'snake' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='snake'); 22 | INSERT INTO types (name) SELECT 'bird' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='bird'); 23 | INSERT INTO types (name) SELECT 'hamster' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='cat'); 24 | 25 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'George', 'Franklin', '110 W. Liberty St.', 'Madison', '6085551023' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=1); 26 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Betty', 'Davis', '638 Cardinal Ave.', 'Sun Prairie', '6085551749' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=2); 27 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Eduardo', 'Rodriquez', '2693 Commerce St.', 'McFarland', '6085558763' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=3); 28 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=4); 29 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=5); 30 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=6); 31 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Jeff', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=7); 32 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Maria', 'Escobito', '345 Maple St.', 'Madison', '6085557683' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=8); 33 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=9); 34 | INSERT INTO owners (first_name, last_name, address, city, telephone) SELECT 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487' WHERE NOT EXISTS (SELECT * FROM owners WHERE id=10); 35 | 36 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Leo', '2000-09-07', 1, 1 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=1); 37 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Basil', '2002-08-06', 6, 2 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=2); 38 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Rosy', '2001-04-17', 2, 3 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=3); 39 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Jewel', '2000-03-07', 2, 3 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=4); 40 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Iggy', '2000-11-30', 3, 4 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=5); 41 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'George', '2000-01-20', 4, 5 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=6); 42 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Samantha', '1995-09-04', 1, 6 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=7); 43 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Max', '1995-09-04', 1, 6 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=8); 44 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Lucky', '1999-08-06', 5, 7 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=9); 45 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Mulligan', '1997-02-24', 2, 8 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=10); 46 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Freddy', '2000-03-09', 5, 9 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=11); 47 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Lucky', '2000-06-24', 2, 10 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=12); 48 | INSERT INTO pets (name, birth_date, type_id, owner_id) SELECT 'Sly', '2002-06-08', 1, 10 WHERE NOT EXISTS (SELECT * FROM pets WHERE id=13); 49 | 50 | INSERT INTO visits (pet_id, visit_date, description) SELECT 7, '2010-03-04', 'rabies shot' WHERE NOT EXISTS (SELECT * FROM visits WHERE id=1); 51 | INSERT INTO visits (pet_id, visit_date, description) SELECT 8, '2011-03-04', 'rabies shot' WHERE NOT EXISTS (SELECT * FROM visits WHERE id=2); 52 | INSERT INTO visits (pet_id, visit_date, description) SELECT 8, '2009-06-04', 'neutered' WHERE NOT EXISTS (SELECT * FROM visits WHERE id=3); 53 | INSERT INTO visits (pet_id, visit_date, description) SELECT 7, '2008-09-04', 'spayed' WHERE NOT EXISTS (SELECT * FROM visits WHERE id=4); 54 | -------------------------------------------------------------------------------- /src/main/resources/static/resources/images/spring-logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 13 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 29 | 30 | 32 | 33 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 61 | 62 | 64 | 66 | 67 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Apache Maven Wrapper startup batch script, version 3.2.0 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 28 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 29 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 30 | @REM e.g. to debug Maven itself, use 31 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 32 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 33 | @REM ---------------------------------------------------------------------------- 34 | 35 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 36 | @echo off 37 | @REM set title of command window 38 | title %0 39 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 40 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 41 | 42 | @REM set %HOME% to equivalent of $HOME 43 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 44 | 45 | @REM Execute a user defined script before this one 46 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 47 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 48 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 49 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 50 | :skipRcPre 51 | 52 | @setlocal 53 | 54 | set ERROR_CODE=0 55 | 56 | @REM To isolate internal variables from possible post scripts, we use another setlocal 57 | @setlocal 58 | 59 | @REM ==== START VALIDATION ==== 60 | if not "%JAVA_HOME%" == "" goto OkJHome 61 | 62 | echo. 63 | echo Error: JAVA_HOME not found in your environment. >&2 64 | echo Please set the JAVA_HOME variable in your environment to match the >&2 65 | echo location of your Java installation. >&2 66 | echo. 67 | goto error 68 | 69 | :OkJHome 70 | if exist "%JAVA_HOME%\bin\java.exe" goto init 71 | 72 | echo. 73 | echo Error: JAVA_HOME is set to an invalid directory. >&2 74 | echo JAVA_HOME = "%JAVA_HOME%" >&2 75 | echo Please set the JAVA_HOME variable in your environment to match the >&2 76 | echo location of your Java installation. >&2 77 | echo. 78 | goto error 79 | 80 | @REM ==== END VALIDATION ==== 81 | 82 | :init 83 | 84 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 85 | @REM Fallback to current working directory if not found. 86 | 87 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 88 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 89 | 90 | set EXEC_DIR=%CD% 91 | set WDIR=%EXEC_DIR% 92 | :findBaseDir 93 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 94 | cd .. 95 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 96 | set WDIR=%CD% 97 | goto findBaseDir 98 | 99 | :baseDirFound 100 | set MAVEN_PROJECTBASEDIR=%WDIR% 101 | cd "%EXEC_DIR%" 102 | goto endDetectBaseDir 103 | 104 | :baseDirNotFound 105 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 106 | cd "%EXEC_DIR%" 107 | 108 | :endDetectBaseDir 109 | 110 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 111 | 112 | @setlocal EnableExtensions EnableDelayedExpansion 113 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 114 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 115 | 116 | :endReadAdditionalConfig 117 | 118 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 123 | 124 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 125 | IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | if "%MVNW_VERBOSE%" == "true" ( 132 | echo Found %WRAPPER_JAR% 133 | ) 134 | ) else ( 135 | if not "%MVNW_REPOURL%" == "" ( 136 | SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 137 | ) 138 | if "%MVNW_VERBOSE%" == "true" ( 139 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 140 | echo Downloading from: %WRAPPER_URL% 141 | ) 142 | 143 | powershell -Command "&{"^ 144 | "$webclient = new-object System.Net.WebClient;"^ 145 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 146 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 147 | "}"^ 148 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ 149 | "}" 150 | if "%MVNW_VERBOSE%" == "true" ( 151 | echo Finished downloading %WRAPPER_JAR% 152 | ) 153 | ) 154 | @REM End of extension 155 | 156 | @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file 157 | SET WRAPPER_SHA_256_SUM="" 158 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 159 | IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B 160 | ) 161 | IF NOT %WRAPPER_SHA_256_SUM%=="" ( 162 | powershell -Command "&{"^ 163 | "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ 164 | "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ 165 | " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ 166 | " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ 167 | " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ 168 | " exit 1;"^ 169 | "}"^ 170 | "}" 171 | if ERRORLEVEL 1 goto error 172 | ) 173 | 174 | @REM Provide a "standardized" way to retrieve the CLI args that will 175 | @REM work with both Windows and non-Windows executions. 176 | set MAVEN_CMD_LINE_ARGS=%* 177 | 178 | %MAVEN_JAVA_EXE% ^ 179 | %JVM_CONFIG_MAVEN_PROPS% ^ 180 | %MAVEN_OPTS% ^ 181 | %MAVEN_DEBUG_OPTS% ^ 182 | -classpath %WRAPPER_JAR% ^ 183 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 184 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 185 | if ERRORLEVEL 1 goto error 186 | goto end 187 | 188 | :error 189 | set ERROR_CODE=1 190 | 191 | :end 192 | @endlocal & set ERROR_CODE=%ERROR_CODE% 193 | 194 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 195 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 196 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 197 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 198 | :skipRcPost 199 | 200 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 201 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 202 | 203 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 204 | 205 | cmd /C exit /B %ERROR_CODE% 206 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/samples/petclinic/service/ClinicServiceTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.samples.petclinic.service; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | import java.time.LocalDate; 22 | import java.util.Collection; 23 | 24 | import org.junit.jupiter.api.Test; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 27 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; 28 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 29 | import org.springframework.context.annotation.ComponentScan; 30 | import org.springframework.data.domain.Page; 31 | import org.springframework.data.domain.Pageable; 32 | import org.springframework.samples.petclinic.owner.Owner; 33 | import org.springframework.samples.petclinic.owner.OwnerRepository; 34 | import org.springframework.samples.petclinic.owner.Pet; 35 | import org.springframework.samples.petclinic.owner.PetType; 36 | import org.springframework.samples.petclinic.owner.Visit; 37 | import org.springframework.samples.petclinic.vet.Vet; 38 | import org.springframework.samples.petclinic.vet.VetRepository; 39 | import org.springframework.stereotype.Service; 40 | import org.springframework.transaction.annotation.Transactional; 41 | 42 | /** 43 | * Integration test of the Service and the Repository layer. 44 | *

45 | * ClinicServiceSpringDataJpaTests subclasses benefit from the following services provided 46 | * by the Spring TestContext Framework: 47 | *

48 | *
    49 | *
  • Spring IoC container caching which spares us unnecessary set up 50 | * time between test execution.
  • 51 | *
  • Dependency Injection of test fixture instances, meaning that we 52 | * don't need to perform application context lookups. See the use of 53 | * {@link Autowired @Autowired} on the instance variable, which uses 54 | * autowiring by type. 55 | *
  • Transaction management, meaning each test method is executed in 56 | * its own transaction, which is automatically rolled back by default. Thus, even if tests 57 | * insert or otherwise change database state, there is no need for a teardown or cleanup 58 | * script. 59 | *
  • An {@link org.springframework.context.ApplicationContext ApplicationContext} is 60 | * also inherited and can be used for explicit bean lookup if necessary.
  • 61 | *
62 | * 63 | * @author Ken Krebs 64 | * @author Rod Johnson 65 | * @author Juergen Hoeller 66 | * @author Sam Brannen 67 | * @author Michael Isvy 68 | * @author Dave Syer 69 | */ 70 | @DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class)) 71 | // Ensure that if the mysql profile is active we connect to the real database: 72 | @AutoConfigureTestDatabase(replace = Replace.NONE) 73 | // @TestPropertySource("/application-postgres.properties") 74 | class ClinicServiceTests { 75 | 76 | @Autowired 77 | protected OwnerRepository owners; 78 | 79 | @Autowired 80 | protected VetRepository vets; 81 | 82 | Pageable pageable; 83 | 84 | @Test 85 | void shouldFindOwnersByLastName() { 86 | Page owners = this.owners.findByLastName("Davis", pageable); 87 | assertThat(owners).hasSize(2); 88 | 89 | owners = this.owners.findByLastName("Daviss", pageable); 90 | assertThat(owners).isEmpty(); 91 | } 92 | 93 | @Test 94 | void shouldFindSingleOwnerWithPet() { 95 | Owner owner = this.owners.findById(1); 96 | assertThat(owner.getLastName()).startsWith("Franklin"); 97 | assertThat(owner.getPets()).hasSize(1); 98 | assertThat(owner.getPets().get(0).getType()).isNotNull(); 99 | assertThat(owner.getPets().get(0).getType().getName()).isEqualTo("cat"); 100 | } 101 | 102 | @Test 103 | @Transactional 104 | void shouldInsertOwner() { 105 | Page owners = this.owners.findByLastName("Schultz", pageable); 106 | int found = (int) owners.getTotalElements(); 107 | 108 | Owner owner = new Owner(); 109 | owner.setFirstName("Sam"); 110 | owner.setLastName("Schultz"); 111 | owner.setAddress("4, Evans Street"); 112 | owner.setCity("Wollongong"); 113 | owner.setTelephone("4444444444"); 114 | this.owners.save(owner); 115 | assertThat(owner.getId().longValue()).isNotEqualTo(0); 116 | 117 | owners = this.owners.findByLastName("Schultz", pageable); 118 | assertThat(owners.getTotalElements()).isEqualTo(found + 1); 119 | } 120 | 121 | @Test 122 | @Transactional 123 | void shouldUpdateOwner() { 124 | Owner owner = this.owners.findById(1); 125 | String oldLastName = owner.getLastName(); 126 | String newLastName = oldLastName + "X"; 127 | 128 | owner.setLastName(newLastName); 129 | this.owners.save(owner); 130 | 131 | // retrieving new name from database 132 | owner = this.owners.findById(1); 133 | assertThat(owner.getLastName()).isEqualTo(newLastName); 134 | } 135 | 136 | @Test 137 | void shouldFindAllPetTypes() { 138 | Collection petTypes = this.owners.findPetTypes(); 139 | 140 | PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1); 141 | assertThat(petType1.getName()).isEqualTo("cat"); 142 | PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4); 143 | assertThat(petType4.getName()).isEqualTo("snake"); 144 | } 145 | 146 | @Test 147 | @Transactional 148 | void shouldInsertPetIntoDatabaseAndGenerateId() { 149 | Owner owner6 = this.owners.findById(6); 150 | int found = owner6.getPets().size(); 151 | 152 | Pet pet = new Pet(); 153 | pet.setName("bowser"); 154 | Collection types = this.owners.findPetTypes(); 155 | pet.setType(EntityUtils.getById(types, PetType.class, 2)); 156 | pet.setBirthDate(LocalDate.now()); 157 | owner6.addPet(pet); 158 | assertThat(owner6.getPets().size()).isEqualTo(found + 1); 159 | 160 | this.owners.save(owner6); 161 | 162 | owner6 = this.owners.findById(6); 163 | assertThat(owner6.getPets().size()).isEqualTo(found + 1); 164 | // checks that id has been generated 165 | pet = owner6.getPet("bowser"); 166 | assertThat(pet.getId()).isNotNull(); 167 | } 168 | 169 | @Test 170 | @Transactional 171 | void shouldUpdatePetName() throws Exception { 172 | Owner owner6 = this.owners.findById(6); 173 | Pet pet7 = owner6.getPet(7); 174 | String oldName = pet7.getName(); 175 | 176 | String newName = oldName + "X"; 177 | pet7.setName(newName); 178 | this.owners.save(owner6); 179 | 180 | owner6 = this.owners.findById(6); 181 | pet7 = owner6.getPet(7); 182 | assertThat(pet7.getName()).isEqualTo(newName); 183 | } 184 | 185 | @Test 186 | void shouldFindVets() { 187 | Collection vets = this.vets.findAll(); 188 | 189 | Vet vet = EntityUtils.getById(vets, Vet.class, 3); 190 | assertThat(vet.getLastName()).isEqualTo("Douglas"); 191 | assertThat(vet.getNrOfSpecialties()).isEqualTo(2); 192 | assertThat(vet.getSpecialties().get(0).getName()).isEqualTo("dentistry"); 193 | assertThat(vet.getSpecialties().get(1).getName()).isEqualTo("surgery"); 194 | } 195 | 196 | @Test 197 | @Transactional 198 | void shouldAddNewVisitForPet() { 199 | Owner owner6 = this.owners.findById(6); 200 | Pet pet7 = owner6.getPet(7); 201 | int found = pet7.getVisits().size(); 202 | Visit visit = new Visit(); 203 | visit.setDescription("test"); 204 | 205 | owner6.addVisit(pet7.getId(), visit); 206 | this.owners.save(owner6); 207 | 208 | owner6 = this.owners.findById(6); 209 | 210 | assertThat(pet7.getVisits()) // 211 | .hasSize(found + 1) // 212 | .allMatch(value -> value.getId() != null); 213 | } 214 | 215 | @Test 216 | void shouldFindVisitsByPetId() throws Exception { 217 | Owner owner6 = this.owners.findById(6); 218 | Pet pet7 = owner6.getPet(7); 219 | Collection visits = pet7.getVisits(); 220 | 221 | assertThat(visits) // 222 | .hasSize(2) // 223 | .element(0) 224 | .extracting(Visit::getDate) 225 | .isNotNull(); 226 | } 227 | 228 | } 229 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Spring PetClinic Sample Application [![Build Status](https://github.com/spring-projects/spring-petclinic/actions/workflows/maven-build.yml/badge.svg)](https://github.com/spring-projects/spring-petclinic/actions/workflows/maven-build.yml) 2 | 3 | [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/spring-projects/spring-petclinic) [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=7517918) 4 | 5 | ## Understanding the Spring Petclinic application with a few diagrams 6 | 7 | [See the presentation here](https://speakerdeck.com/michaelisvy/spring-petclinic-sample-application) 8 | 9 | ## Run Petclinic locally 10 | 11 | Spring Petclinic is a [Spring Boot](https://spring.io/guides/gs/spring-boot) application built using [Maven](https://spring.io/guides/gs/maven/) or [Gradle](https://spring.io/guides/gs/gradle/). You can build a jar file and run it from the command line (it should work just as well with Java 17 or newer): 12 | 13 | ```bash 14 | git clone https://github.com/spring-projects/spring-petclinic.git 15 | cd spring-petclinic 16 | ./mvnw package 17 | java -jar target/*.jar 18 | ``` 19 | 20 | You can then access the Petclinic at . 21 | 22 | petclinic-screenshot 23 | 24 | Or you can run it from Maven directly using the Spring Boot Maven plugin. If you do this, it will pick up changes that you make in the project immediately (changes to Java source files require a compile as well - most people use an IDE for this): 25 | 26 | ```bash 27 | ./mvnw spring-boot:run 28 | ``` 29 | 30 | > NOTE: If you prefer to use Gradle, you can build the app using `./gradlew build` and look for the jar file in `build/libs`. 31 | 32 | ## Building a Container 33 | 34 | There is no `Dockerfile` in this project. You can build a container image (if you have a docker daemon) using the Spring Boot build plugin: 35 | 36 | ```bash 37 | ./mvnw spring-boot:build-image 38 | ``` 39 | 40 | ## In case you find a bug/suggested improvement for Spring Petclinic 41 | 42 | Our issue tracker is available [here](https://github.com/spring-projects/spring-petclinic/issues). 43 | 44 | ## Database configuration 45 | 46 | In its default configuration, Petclinic uses an in-memory database (H2) which 47 | gets populated at startup with data. The h2 console is exposed at `http://localhost:8080/h2-console`, 48 | and it is possible to inspect the content of the database using the `jdbc:h2:mem:` URL. The UUID is printed at startup to the console. 49 | 50 | A similar setup is provided for MySQL and PostgreSQL if a persistent database configuration is needed. Note that whenever the database type changes, the app needs to run with a different profile: `spring.profiles.active=mysql` for MySQL or `spring.profiles.active=postgres` for PostgreSQL. 51 | 52 | You can start MySQL or PostgreSQL locally with whatever installer works for your OS or use docker: 53 | 54 | ```bash 55 | docker run -e MYSQL_USER=petclinic -e MYSQL_PASSWORD=petclinic -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:8.2 56 | ``` 57 | 58 | or 59 | 60 | ```bash 61 | docker run -e POSTGRES_USER=petclinic -e POSTGRES_PASSWORD=petclinic -e POSTGRES_DB=petclinic -p 5432:5432 postgres:16.1 62 | ``` 63 | 64 | Further documentation is provided for [MySQL](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources/db/mysql/petclinic_db_setup_mysql.txt) 65 | and [PostgreSQL](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources/db/postgres/petclinic_db_setup_postgres.txt). 66 | 67 | Instead of vanilla `docker` you can also use the provided `docker-compose.yml` file to start the database containers. Each one has a profile just like the Spring profile: 68 | 69 | ```bash 70 | docker-compose --profile mysql up 71 | ``` 72 | 73 | or 74 | 75 | ```bash 76 | docker-compose --profile postgres up 77 | ``` 78 | 79 | ## Test Applications 80 | 81 | At development time we recommend you use the test applications set up as `main()` methods in `PetClinicIntegrationTests` (using the default H2 database and also adding Spring Boot Devtools), `MySqlTestApplication` and `PostgresIntegrationTests`. These are set up so that you can run the apps in your IDE to get fast feedback and also run the same classes as integration tests against the respective database. The MySql integration tests use Testcontainers to start the database in a Docker container, and the Postgres tests use Docker Compose to do the same thing. 82 | 83 | ## Compiling the CSS 84 | 85 | There is a `petclinic.css` in `src/main/resources/static/resources/css`. It was generated from the `petclinic.scss` source, combined with the [Bootstrap](https://getbootstrap.com/) library. If you make changes to the `scss`, or upgrade Bootstrap, you will need to re-compile the CSS resources using the Maven profile "css", i.e. `./mvnw package -P css`. There is no build profile for Gradle to compile the CSS. 86 | 87 | ## Working with Petclinic in your IDE 88 | 89 | ### Prerequisites 90 | 91 | The following items should be installed in your system: 92 | 93 | - Java 17 or newer (full JDK, not a JRE) 94 | - [Git command line tool](https://help.github.com/articles/set-up-git) 95 | - Your preferred IDE 96 | - Eclipse with the m2e plugin. Note: when m2e is available, there is an m2 icon in `Help -> About` dialog. If m2e is 97 | not there, follow the install process [here](https://www.eclipse.org/m2e/) 98 | - [Spring Tools Suite](https://spring.io/tools) (STS) 99 | - [IntelliJ IDEA](https://www.jetbrains.com/idea/) 100 | - [VS Code](https://code.visualstudio.com) 101 | 102 | ### Steps 103 | 104 | 1. On the command line run: 105 | 106 | ```bash 107 | git clone https://github.com/spring-projects/spring-petclinic.git 108 | ``` 109 | 110 | 1. Inside Eclipse or STS: 111 | 112 | Open the project via `File -> Import -> Maven -> Existing Maven project`, then select the root directory of the cloned repo. 113 | 114 | Then either build on the command line `./mvnw generate-resources` or use the Eclipse launcher (right-click on project and `Run As -> Maven install`) to generate the CSS. Run the application's main method by right-clicking on it and choosing `Run As -> Java Application`. 115 | 116 | 1. Inside IntelliJ IDEA: 117 | 118 | In the main menu, choose `File -> Open` and select the Petclinic [pom.xml](pom.xml). Click on the `Open` button. 119 | 120 | - CSS files are generated from the Maven build. You can build them on the command line `./mvnw generate-resources` or right-click on the `spring-petclinic` project then `Maven -> Generates sources and Update Folders`. 121 | 122 | - A run configuration named `PetClinicApplication` should have been created for you if you're using a recent Ultimate version. Otherwise, run the application by right-clicking on the `PetClinicApplication` main class and choosing `Run 'PetClinicApplication'`. 123 | 124 | 1. Navigate to the Petclinic 125 | 126 | Visit [http://localhost:8080](http://localhost:8080) in your browser. 127 | 128 | ## Looking for something in particular? 129 | 130 | |Spring Boot Configuration | Class or Java property files | 131 | |--------------------------|---| 132 | |The Main Class | [PetClinicApplication](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java) | 133 | |Properties Files | [application.properties](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources) | 134 | |Caching | [CacheConfiguration](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java) | 135 | 136 | ## Interesting Spring Petclinic branches and forks 137 | 138 | The Spring Petclinic "main" branch in the [spring-projects](https://github.com/spring-projects/spring-petclinic) 139 | GitHub org is the "canonical" implementation based on Spring Boot and Thymeleaf. There are 140 | [quite a few forks](https://spring-petclinic.github.io/docs/forks.html) in the GitHub org 141 | [spring-petclinic](https://github.com/spring-petclinic). If you are interested in using a different technology stack to implement the Pet Clinic, please join the community there. 142 | 143 | ## Interaction with other open-source projects 144 | 145 | One of the best parts about working on the Spring Petclinic application is that we have the opportunity to work in direct contact with many Open Source projects. We found bugs/suggested improvements on various topics such as Spring, Spring Data, Bean Validation and even Eclipse! In many cases, they've been fixed/implemented in just a few days. 146 | Here is a list of them: 147 | 148 | | Name | Issue | 149 | |------|-------| 150 | | Spring JDBC: simplify usage of NamedParameterJdbcTemplate | [SPR-10256](https://jira.springsource.org/browse/SPR-10256) and [SPR-10257](https://jira.springsource.org/browse/SPR-10257) | 151 | | Bean Validation / Hibernate Validator: simplify Maven dependencies and backward compatibility |[HV-790](https://hibernate.atlassian.net/browse/HV-790) and [HV-792](https://hibernate.atlassian.net/browse/HV-792) | 152 | | Spring Data: provide more flexibility when working with JPQL queries | [DATAJPA-292](https://jira.springsource.org/browse/DATAJPA-292) | 153 | 154 | ## Contributing 155 | 156 | The [issue tracker](https://github.com/spring-projects/spring-petclinic/issues) is the preferred channel for bug reports, feature requests and submitting pull requests. 157 | 158 | For pull requests, editor preferences are available in the [editor config](.editorconfig) for easy use in common text editors. Read more and download plugins at . If you have not previously done so, please fill out and submit the [Contributor License Agreement](https://cla.pivotal.io/sign/spring). 159 | 160 | ## License 161 | 162 | The Spring PetClinic sample application is released under version 2.0 of the [Apache License](https://www.apache.org/licenses/LICENSE-2.0). 163 | --------------------------------------------------------------------------------