Compare commits

..

2 commits

Author SHA1 Message Date
Sébastien Deleuze
a2672fef9b Remove hardcoded spring.profiles.active=mysql 2022-10-25 21:42:15 +02:00
Dave Syer
e54af39b53 Ensure MySQL works as well. 2022-10-25 21:42:15 +02:00
71 changed files with 2919 additions and 5533 deletions

View file

@ -1,11 +1,13 @@
# Not actually used by the devcontainer, but it is used by gitpod
ARG VARIANT=17-bullseye ARG VARIANT=17-bullseye
FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT} FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT}
ARG NODE_VERSION="none" ARG NODE_VERSION="none"
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
ARG USER=vscode ARG USER=vscode
VOLUME /home/$USER/.m2 VOLUME /home/$USER/.m2
VOLUME /home/$USER/.gradle VOLUME /home/$USER/.gradle
ARG JAVA_VERSION=17.0.7-ms
ARG JAVA_VERSION=17.0.4.1-ms
RUN sudo mkdir /home/$USER/.m2 /home/$USER/.gradle && sudo chown $USER:$USER /home/$USER/.m2 /home/$USER/.gradle RUN sudo mkdir /home/$USER/.m2 /home/$USER/.gradle && sudo chown $USER:$USER /home/$USER/.m2 /home/$USER/.gradle
RUN bash -lc '. /usr/local/sdkman/bin/sdkman-init.sh && sdk install java $JAVA_VERSION && sdk use java $JAVA_VERSION' RUN bash -lc '. /usr/local/sdkman/bin/sdkman-init.sh && sdk install java $JAVA_VERSION && sdk use java $JAVA_VERSION'

View file

@ -1,25 +1,32 @@
{ {
"name": "Java", "name": "Petclinic",
"image": "mcr.microsoft.com/devcontainers/base:ubuntu", "dockerFile": "Dockerfile",
"features": { "runArgs": [
"ghcr.io/devcontainers/features/java:1": { "--cap-add=SYS_PTRACE",
"version": "21-oracle", "--security-opt",
"jdkDistro": "oracle" "seccomp=unconfined",
}, "--mount",
"ghcr.io/devcontainers/features/azure-cli:1": {}, "type=bind,source=${env:HOME}/.m2,target=/home/vscode/.m2",
"ghcr.io/devcontainers/features/docker-in-docker:2": {}, "--mount",
"ghcr.io/devcontainers/features/github-cli:1": {} "type=bind,source=${env:HOME}/.gradle,target=/home/vscode/.gradle",
}, "--env",
"GRADLE_USER_HOME=/home/vscode/.gradle"
"customizations": { ],
"vscode": { "initializeCommand": "mkdir -p ${env:HOME}/.m2 ${env:HOME}/.gradle",
"settings": {}, "postCreateCommand": "sudo chown vscode:vscode /home/vscode/.m2 /home/vscode/.gradle",
"extensions": [ "remoteUser": "vscode",
"redhat.vscode-xml", "features": {
"visualstudioexptteam.vscodeintellicode", "docker-in-docker": "latest"
"vscjava.vscode-java-pack" },
] "extensions": [
} "vscjava.vscode-java-pack",
}, "redhat.vscode-xml",
"remoteUser": "vscode" "Pivotal.vscode-boot-dev-pack",
"mhutchie.git-graph"
],
"forwardPorts": [8080],
"settings": {
"java.import.gradle.enabled": false,
"java.server.launchMode": "Standard"
}
} }

View file

@ -19,6 +19,3 @@ indent_style = space
[*.{html,sql,less}] [*.{html,sql,less}]
indent_size = 2 indent_size = 2
[*.gradle]
indent_size = 2

5
.gitattributes vendored
View file

@ -1,5 +0,0 @@
mvnw text eol=lf
*.java text eol=lf
/gradlew text eol=lf
*.bat text eol=crlf

View file

@ -1,5 +1,5 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/use-cases-and-examples/building-and-testing/building-and-testing-java-with-maven # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Java CI with Maven name: Java CI with Maven
@ -15,15 +15,15 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
java: [ '17' ] java: [ '8', '11', '17' ]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Set up JDK ${{matrix.java}} - name: Set up JDK ${{matrix.java}}
uses: actions/setup-java@v4 uses: actions/setup-java@v2
with: with:
java-version: ${{matrix.java}} java-version: ${{matrix.java}}
distribution: 'adopt' distribution: 'adopt'
cache: maven cache: maven
- name: Build with Maven Wrapper - name: Build with Maven Wrapper
run: ./mvnw -B verify run: ./mvnw -B package

54
.gitignore vendored
View file

@ -1,51 +1,17 @@
HELP.md target/*
pom.xml.bak bin/*
target/ build/*
!.mvn/wrapper/maven-wrapper.jar .gradle/*
!**/src/main/**/target/ .settings/*
!**/src/test/**/target/
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.attach_pid*
.apt_generated
.classpath .classpath
.factorypath
.project .project
.settings .factorypath
.springBeans .attach_pid*
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea .idea
*.iws
*.iml *.iml
*.ipr /target
out/ .sts4-cache/
!**/src/main/**/out/ .vscode
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### SDK Man ###
.sdkmanrc
### CSS ###
_site/ _site/
*.css *.css
!petclinic.css !petclinic.css

117
.mvn/wrapper/MavenWrapperDownloader.java vendored Normal file
View file

@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0'
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -1,19 +1,3 @@
# Licensed to the Apache Software Foundation (ASF) under one distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
# or more contributor license agreements. See the NOTICE file wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

1
.springjavaformatconfig Normal file
View file

@ -0,0 +1 @@
java-baseline=8

162
README.md
View file

@ -1,162 +0,0 @@
# 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)[![Build Status](https://github.com/spring-projects/spring-petclinic/actions/workflows/gradle-build.yml/badge.svg)](https://github.com/spring-projects/spring-petclinic/actions/workflows/gradle-build.yml)
[![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)
## Understanding the Spring Petclinic application with a few diagrams
[See the presentation here](https://speakerdeck.com/michaelisvy/spring-petclinic-sample-application)
## Run Petclinic locally
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):
```bash
git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
./mvnw package
java -jar target/*.jar
```
You can then access the Petclinic at <http://localhost:8080/>.
<img width="1042" alt="petclinic-screenshot" src="https://cloud.githubusercontent.com/assets/838318/19727082/2aee6d6c-9b8e-11e6-81fe-e889a5ddfded.png">
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):
```bash
./mvnw spring-boot:run
```
> NOTE: If you prefer to use Gradle, you can build the app using `./gradlew build` and look for the jar file in `build/libs`.
## Building a Container
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:
```bash
./mvnw spring-boot:build-image
```
## In case you find a bug/suggested improvement for Spring Petclinic
Our issue tracker is available [here](https://github.com/spring-projects/spring-petclinic/issues).
## Database configuration
In its default configuration, Petclinic uses an in-memory database (H2) which
gets populated at startup with data. The h2 console is exposed at `http://localhost:8080/h2-console`,
and it is possible to inspect the content of the database using the `jdbc:h2:mem:<uuid>` URL. The UUID is printed at startup to the console.
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. See the [Spring Boot documentation](https://docs.spring.io/spring-boot/how-to/properties-and-configuration.html#howto.properties-and-configuration.set-active-spring-profiles) for more detail on how to set the active profile.
You can start MySQL or PostgreSQL locally with whatever installer works for your OS or use docker:
```bash
docker run -e MYSQL_USER=petclinic -e MYSQL_PASSWORD=petclinic -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:9.1
```
or
```bash
docker run -e POSTGRES_USER=petclinic -e POSTGRES_PASSWORD=petclinic -e POSTGRES_DB=petclinic -p 5432:5432 postgres:17.0
```
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)
and [PostgreSQL](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources/db/postgres/petclinic_db_setup_postgres.txt).
Instead of vanilla `docker` you can also use the provided `docker-compose.yml` file to start the database containers. Each one has a service named after the Spring profile:
```bash
docker compose up mysql
```
or
```bash
docker compose up postgres
```
## Test Applications
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.
## Compiling the CSS
There is a `petclinic.css` in `src/main/resources/static/resources/css`. It was generated from the `petclinic.scss` source, combined with the [Bootstrap](https://getbootstrap.com/) library. If you make changes to the `scss`, or upgrade Bootstrap, you will need to re-compile the CSS resources using the Maven profile "css", i.e. `./mvnw package -P css`. There is no build profile for Gradle to compile the CSS.
## Working with Petclinic in your IDE
### Prerequisites
The following items should be installed in your system:
- Java 17 or newer (full JDK, not a JRE)
- [Git command line tool](https://help.github.com/articles/set-up-git)
- Your preferred IDE
- Eclipse with the m2e plugin. Note: when m2e is available, there is an m2 icon in `Help -> About` dialog. If m2e is
not there, follow the install process [here](https://www.eclipse.org/m2e/)
- [Spring Tools Suite](https://spring.io/tools) (STS)
- [IntelliJ IDEA](https://www.jetbrains.com/idea/)
- [VS Code](https://code.visualstudio.com)
### Steps
1. On the command line run:
```bash
git clone https://github.com/spring-projects/spring-petclinic.git
```
1. Inside Eclipse or STS:
Open the project via `File -> Import -> Maven -> Existing Maven project`, then select the root directory of the cloned repo.
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`.
1. Inside IntelliJ IDEA:
In the main menu, choose `File -> Open` and select the Petclinic [pom.xml](pom.xml). Click on the `Open` button.
- 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`.
- 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'`.
1. Navigate to the Petclinic
Visit [http://localhost:8080](http://localhost:8080) in your browser.
## Looking for something in particular?
|Spring Boot Configuration | Class or Java property files |
|--------------------------|---|
|The Main Class | [PetClinicApplication](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java) |
|Properties Files | [application.properties](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources) |
|Caching | [CacheConfiguration](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java) |
## Interesting Spring Petclinic branches and forks
The Spring Petclinic "main" branch in the [spring-projects](https://github.com/spring-projects/spring-petclinic)
GitHub org is the "canonical" implementation based on Spring Boot and Thymeleaf. There are
[quite a few forks](https://spring-petclinic.github.io/docs/forks.html) in the GitHub org
[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.
## Interaction with other open-source projects
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.
Here is a list of them:
| Name | Issue |
|------|-------|
| 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) |
| 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) |
| Spring Data: provide more flexibility when working with JPQL queries | [DATAJPA-292](https://jira.springsource.org/browse/DATAJPA-292) |
## Contributing
The [issue tracker](https://github.com/spring-projects/spring-petclinic/issues) is the preferred channel for bug reports, feature requests and submitting pull requests.
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 <https://editorconfig.org>. If you have not previously done so, please fill out and submit the [Contributor License Agreement](https://cla.pivotal.io/sign/spring).
## License
The Spring PetClinic sample application is released under version 2.0 of the [Apache License](https://www.apache.org/licenses/LICENSE-2.0).

View file

@ -1,91 +1,40 @@
plugins { plugins {
id 'org.springframework.boot' version '2.7.3'
id 'io.spring.dependency-management' version '1.0.13.RELEASE'
id 'java' id 'java'
id 'org.springframework.boot' version '3.4.0'
id 'io.spring.dependency-management' version '1.1.6'
id 'org.graalvm.buildtools.native' version '0.10.3'
id 'org.cyclonedx.bom' version '1.10.0'
id 'io.spring.javaformat' version '0.0.43'
id "io.spring.nohttp" version "0.0.11"
} }
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'checkstyle'
apply plugin: 'io.spring.javaformat'
gradle.startParameter.excludedTaskNames += [ "checkFormatAot", "checkFormatAotTest" ]
group = 'org.springframework.samples' group = 'org.springframework.samples'
version = '3.4.0' version = '2.7.3'
sourceCompatibility = '11'
java {
sourceCompatibility = JavaVersion.VERSION_17
}
repositories { repositories {
mavenCentral() mavenCentral()
} }
ext.checkstyleVersion = "10.20.1"
ext.springJavaformatCheckstyleVersion = "0.0.43"
ext.webjarsLocatorLiteVersion = "1.0.1"
ext.webjarsFontawesomeVersion = "4.7.0" ext.webjarsFontawesomeVersion = "4.7.0"
ext.webjarsBootstrapVersion = "5.3.3" ext.webjarsBootstrapVersion = "5.1.3"
dependencies { dependencies {
// Workaround for AOT issue (https://github.com/spring-projects/spring-framework/pull/33949) -->
implementation 'io.projectreactor:reactor-core'
implementation 'org.springframework.boot:spring-boot-starter-cache' implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'io.micrometer:micrometer-registry-prometheus'
implementation 'javax.cache:cache-api' implementation 'javax.cache:cache-api'
implementation 'jakarta.xml.bind:jakarta.xml.bind-api'
runtimeOnly 'org.springframework.boot:spring-boot-starter-actuator' runtimeOnly 'org.springframework.boot:spring-boot-starter-actuator'
runtimeOnly "org.webjars:webjars-locator-lite:${webjarsLocatorLiteVersion}"
runtimeOnly "org.webjars.npm:bootstrap:${webjarsBootstrapVersion}" runtimeOnly "org.webjars.npm:bootstrap:${webjarsBootstrapVersion}"
runtimeOnly "org.webjars.npm:font-awesome:${webjarsFontawesomeVersion}" runtimeOnly "org.webjars.npm:font-awesome:${webjarsFontawesomeVersion}"
runtimeOnly 'com.github.ben-manes.caffeine:caffeine' runtimeOnly 'org.ehcache:ehcache'
runtimeOnly 'com.h2database:h2' runtimeOnly 'com.h2database:h2'
runtimeOnly 'com.mysql:mysql-connector-j' runtimeOnly 'mysql:mysql-connector-java'
runtimeOnly 'org.postgresql:postgresql' runtimeOnly 'org.postgresql:postgresql'
developmentOnly 'org.springframework.boot:spring-boot-devtools' developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.springframework.boot:spring-boot-docker-compose'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:mysql'
checkstyle "io.spring.javaformat:spring-javaformat-checkstyle:${springJavaformatCheckstyleVersion}"
checkstyle "com.puppycrawl.tools:checkstyle:${checkstyleVersion}"
} }
tasks.named('test') { tasks.named('test') {
useJUnitPlatform() useJUnitPlatform()
} }
checkstyle {
configDirectory = project.file('src/checkstyle')
configFile = file('src/checkstyle/nohttp-checkstyle.xml')
}
checkstyleNohttp {
configDirectory = project.file('src/checkstyle')
configFile = file('src/checkstyle/nohttp-checkstyle.xml')
}
tasks.named("formatMain").configure { dependsOn("checkstyleMain") }
tasks.named("formatMain").configure { dependsOn("checkstyleNohttp") }
tasks.named("formatTest").configure { dependsOn("checkstyleTest") }
tasks.named("formatTest").configure { dependsOn("checkstyleNohttp") }
checkstyleAot.enabled = false
checkstyleAotTest.enabled = false
checkFormatAot.enabled = false
checkFormatAotTest.enabled = false
formatAot.enabled = false
formatAotTest.enabled = false

View file

@ -1,6 +1,8 @@
version: "2.2"
services: services:
mysql: mysql:
image: mysql:9.1 image: mysql:5.7
ports: ports:
- "3306:3306" - "3306:3306"
environment: environment:
@ -12,7 +14,7 @@ services:
volumes: volumes:
- "./conf.d:/etc/mysql/conf.d:ro" - "./conf.d:/etc/mysql/conf.d:ro"
postgres: postgres:
image: postgres:17.0 image: postgres:14.1
ports: ports:
- "5432:5432" - "5432:5432"
environment: environment:

Binary file not shown.

View file

@ -1,7 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

44
gradlew vendored
View file

@ -15,8 +15,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@ -57,7 +55,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@ -82,12 +80,13 @@ do
esac esac
done done
# This is normally unused APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
' "$PWD" ) || exit DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@ -134,29 +133,22 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
if ! command -v java >/dev/null 2>&1 which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@ -201,15 +193,11 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# Collect all arguments for the java command: # * put everything else in single quotes, so that it's not re-expanded.
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -217,12 +205,6 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.

183
gradlew.bat vendored
View file

@ -1,94 +1,89 @@
@rem @rem
@rem Copyright 2015 the original author or authors. @rem Copyright 2015 the original author or authors.
@rem @rem
@rem Licensed under the Apache License, Version 2.0 (the "License"); @rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License. @rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at @rem You may obtain a copy of the License at
@rem @rem
@rem https://www.apache.org/licenses/LICENSE-2.0 @rem https://www.apache.org/licenses/LICENSE-2.0
@rem @rem
@rem Unless required by applicable law or agreed to in writing, software @rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS, @rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem @if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@if "%DEBUG%"=="" @echo off @rem
@rem ########################################################################## @rem Gradle startup script for Windows
@rem @rem
@rem Gradle startup script for Windows @rem ##########################################################################
@rem
@rem ########################################################################## @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set DIRNAME=%~dp0 set APP_BASE_NAME=%~n0
if "%DIRNAME%"=="" set DIRNAME=. set APP_HOME=%DIRNAME%
@rem This is normally unused
set APP_BASE_NAME=%~n0 @rem Resolve any "." and ".." in APP_HOME to make it shorter.
set APP_HOME=%DIRNAME% for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Resolve any "." and ".." in APP_HOME to make it shorter. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Find java.exe
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" if defined JAVA_HOME goto findJavaFromJavaHome
@rem Find java.exe set JAVA_EXE=java.exe
if defined JAVA_HOME goto findJavaFromJavaHome %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 echo.
if %ERRORLEVEL% equ 0 goto execute echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo location of your Java installation.
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 goto fail
echo location of your Java installation. 1>&2
:findJavaFromJavaHome
goto fail set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% if exist "%JAVA_EXE%" goto execute
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
echo.
if exist "%JAVA_EXE%" goto execute echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo location of your Java installation.
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 goto fail
echo location of your Java installation. 1>&2
:execute
goto fail @rem Setup the command line
:execute set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
@rem Execute Gradle :end
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:end
@rem End local scope for the variables with windows NT shell :fail
if %ERRORLEVEL% equ 0 goto mainEnd rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
:fail if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of exit /b 1
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL% :mainEnd
if %EXIT_CODE% equ 0 set EXIT_CODE=1 if "%OS%"=="Windows_NT" endlocal
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE% :omega
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -1,73 +0,0 @@
---
apiVersion: v1
kind: Secret
metadata:
name: demo-db
type: servicebinding.io/postgresql
stringData:
type: "postgresql"
provider: "postgresql"
host: "demo-db"
port: "5432"
database: "petclinic"
username: "user"
password: "pass"
---
apiVersion: v1
kind: Service
metadata:
name: demo-db
spec:
ports:
- port: 5432
selector:
app: demo-db
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: demo-db
labels:
app: demo-db
spec:
selector:
matchLabels:
app: demo-db
template:
metadata:
labels:
app: demo-db
spec:
containers:
- image: postgres:17
name: postgresql
env:
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: demo-db
key: username
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: demo-db
key: password
- name: POSTGRES_DB
valueFrom:
secretKeyRef:
name: demo-db
key: database
ports:
- containerPort: 5432
name: postgresql
livenessProbe:
tcpSocket:
port: postgresql
readinessProbe:
tcpSocket:
port: postgresql
startupProbe:
tcpSocket:
port: postgresql

View file

@ -1,64 +0,0 @@
---
apiVersion: v1
kind: Service
metadata:
name: petclinic
spec:
type: NodePort
ports:
- port: 80
targetPort: 8080
selector:
app: petclinic
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: petclinic
labels:
app: petclinic
spec:
replicas: 1
selector:
matchLabels:
app: petclinic
template:
metadata:
labels:
app: petclinic
spec:
containers:
- name: workload
image: dsyer/petclinic
env:
- name: SPRING_PROFILES_ACTIVE
value: postgres
- name: SERVICE_BINDING_ROOT
value: /bindings
- name: SPRING_APPLICATION_JSON
value: |
{
"management.endpoint.health.probes.add-additional-paths": true
}
ports:
- name: http
containerPort: 8080
livenessProbe:
httpGet:
path: /livez
port: http
readinessProbe:
httpGet:
path: /readyz
port: http
volumeMounts:
- mountPath: /bindings/secret
name: binding
readOnly: true
volumes:
- name: binding
projected:
sources:
- secret:
name: demo-db

481
mvnw vendored
View file

@ -8,7 +8,7 @@
# "License"); you may not use this file except in compliance # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at # with the License. You may obtain a copy of the License at
# #
# https://www.apache.org/licenses/LICENSE-2.0 # https://www.apache.org/licenses/LICENSE-2.0'
# #
# Unless required by applicable law or agreed to in writing, # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an # software distributed under the License is distributed on an
@ -19,241 +19,292 @@
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2 # Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
# #
# Optional ENV vars # Optional ENV vars
# ----------------- # -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source # M2_HOME - location of maven2's installed home dir
# MVNW_REPOURL - repo url base for downloading maven distribution # MAVEN_OPTS - parameters passed to the Java VM when running Maven
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven # e.g. to debug Maven itself, use
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
set -euf if [ -z "$MAVEN_SKIP_RC" ] ; then
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support. if [ -f /etc/mavenrc ] ; then
native_path() { printf %s\\n "$1"; } . /etc/mavenrc
case "$(uname)" in fi
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD if [ -f "$HOME/.mavenrc" ] ; then
set_java_home() { . "$HOME/.mavenrc"
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched fi
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then fi
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 # OS specific support. $var _must_ be set to either true or false.
return 1 cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi fi
fi fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;; ;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac esac
# apply MVNW_REPOURL and calculate MAVEN_HOME if [ -z "$JAVA_HOME" ] ; then
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> if [ -r /etc/gentoo-release ] ; then
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" JAVA_HOME=`java-config --jre-home`
distributionUrlName="${distributionUrl##*/}" fi
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi fi
case "${distributionUrl-}" in if [ -z "$M2_HOME" ] ; then
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; ## resolve links - $0 may be a link to maven's home
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; PRG="$0"
esac
# prepare tmp dir # need this for relative symlinks
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then while [ -h "$PRG" ] ; do
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } ls=`ls -ld "$PRG"`
trap clean HUP INT TERM EXIT link=`expr "$ls" : '.*-> \(.*\)$'`
else if expr "$link" : '/.*' > /dev/null; then
die "cannot create temp dir" PRG="$link"
fi else
PRG="`dirname "$PRG"`/$link"
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi fi
elif command -v shasum >/dev/null; then done
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi fi
else else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 JAVACMD="`which java`"
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi fi
fi fi
# unzip and move if [ ! -x "$JAVACMD" ] ; then
if command -v unzip >/dev/null; then echo "Error: JAVA_HOME is not defined correctly." >&2
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" if [ "$MVNW_VERBOSE" = true ]; then
fi echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" fi
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
clean || : if command -v wget > /dev/null; then
exec_maven "$@" if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

263
mvnw.cmd vendored
View file

@ -1,4 +1,3 @@
<# : batch portion
@REM ---------------------------------------------------------------------------- @REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one @REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file @REM or more contributor license agreements. See the NOTICE file
@ -8,7 +7,7 @@
@REM "License"); you may not use this file except in compliance @REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at @REM with the License. You may obtain a copy of the License at
@REM @REM
@REM https://www.apache.org/licenses/LICENSE-2.0 @REM https://www.apache.org/licenses/LICENSE-2.0'
@REM @REM
@REM Unless required by applicable law or agreed to in writing, @REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an @REM software distributed under the License is distributed on an
@ -19,131 +18,165 @@
@REM ---------------------------------------------------------------------------- @REM ----------------------------------------------------------------------------
@REM ---------------------------------------------------------------------------- @REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2 @REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM @REM
@REM Optional ENV vars @REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution @REM M2_HOME - location of maven2's installed home dir
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ---------------------------------------------------------------------------- @REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@SET __MVNW_CMD__= @echo off
@SET __MVNW_ERROR__= @REM set title of command window
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% title %0
@SET PSModulePath= @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
) )
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop" @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
if ($env:MVNW_VERBOSE -eq "true") { @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
$VerbosePreference = "Continue" if exist %WRAPPER_JAR% (
} if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties powershell -Command "&{"^
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl "$webclient = new-object System.Net.WebClient;"^
if (!$distributionUrl) { "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
} "}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { @REM Provide a "standardized" way to retrieve the CLI args that will
"maven-mvnd-*" { @REM work with both Windows and non-Windows executions.
$USE_MVND = $true set MAVEN_CMD_LINE_ARGS=%*
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> if ERRORLEVEL 1 goto error
if ($env:MVNW_REPOURL) { goto end
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { :error
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" set ERROR_CODE=1
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { :end
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" @endlocal & set ERROR_CODE=%ERROR_CODE%
}
# prepare tmp dir if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile @REM check for post script, once with legacy .bat ending and once with .cmd ending
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
trap { :skipRcPost
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
# Download and Install Apache Maven if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient exit /B %ERROR_CODE%
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

210
pom.xml
View file

@ -1,18 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-petclinic</artifactId>
<version>3.0.0-SNAPSHOT</version>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version> <version>3.0.0-RC1</version>
<relativePath></relativePath>
</parent> </parent>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-petclinic</artifactId>
<version>3.4.0-SNAPSHOT</version>
<name>petclinic</name> <name>petclinic</name>
<properties> <properties>
@ -21,22 +18,14 @@
<java.version>17</java.version> <java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Important for reproducible builds. Update using e.g. ./mvnw versions:set
-DnewVersion=... -->
<project.build.outputTimestamp>2024-11-28T14:37:52Z</project.build.outputTimestamp>
<!-- Web dependencies --> <!-- Web dependencies -->
<webjars-locator.version>1.0.1</webjars-locator.version> <webjars-bootstrap.version>5.1.3</webjars-bootstrap.version>
<webjars-bootstrap.version>5.3.3</webjars-bootstrap.version>
<webjars-font-awesome.version>4.7.0</webjars-font-awesome.version> <webjars-font-awesome.version>4.7.0</webjars-font-awesome.version>
<checkstyle.version>10.20.1</checkstyle.version> <jacoco.version>0.8.7</jacoco.version>
<jacoco.version>0.8.12</jacoco.version> <nohttp-checkstyle.version>0.0.10</nohttp-checkstyle.version>
<libsass.version>0.2.29</libsass.version> <spring-format.version>0.0.31</spring-format.version>
<lifecycle-mapping>1.0.0</lifecycle-mapping>
<maven-checkstyle.version>3.6.0</maven-checkstyle.version>
<nohttp-checkstyle.version>0.0.11</nohttp-checkstyle.version>
<spring-format.version>0.0.43</spring-format.version>
</properties> </properties>
@ -71,11 +60,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<!-- Workaround for AOT issue (https://github.com/spring-projects/spring-framework/pull/33949) -->
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<!-- Databases - Uses H2 by default --> <!-- Databases - Uses H2 by default -->
<dependency> <dependency>
@ -84,8 +68,8 @@
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId> <artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -94,7 +78,7 @@
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- Caching --> <!-- caching -->
<dependency> <dependency>
<groupId>javax.cache</groupId> <groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId> <artifactId>cache-api</artifactId>
@ -104,12 +88,7 @@
<artifactId>caffeine</artifactId> <artifactId>caffeine</artifactId>
</dependency> </dependency>
<!-- Webjars --> <!-- webjars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-lite</artifactId>
<version>${webjars-locator.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.webjars.npm</groupId> <groupId>org.webjars.npm</groupId>
<artifactId>bootstrap</artifactId> <artifactId>bootstrap</artifactId>
@ -120,31 +99,12 @@
<artifactId>font-awesome</artifactId> <artifactId>font-awesome</artifactId>
<version>${webjars-font-awesome.version}</version> <version>${webjars-font-awesome.version}</version>
</dependency> </dependency>
<!-- end of webjars -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId> <artifactId>spring-boot-devtools</artifactId>
<scope>test</scope> <optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-docker-compose</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -152,59 +112,32 @@
<artifactId>jakarta.xml.bind-api</artifactId> <artifactId>jakarta.xml.bind-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>enforce-java</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireJavaVersion>
<message>This build requires at least Java ${java.version},
update your JVM, and
run the build again</message>
<version>${java.version}</version>
</requireJavaVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>io.spring.javaformat</groupId> <groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId> <artifactId>spring-javaformat-maven-plugin</artifactId>
<version>${spring-format.version}</version> <version>${spring-format.version}</version>
<executions> <executions>
<execution> <execution>
<phase>validate</phase>
<goals> <goals>
<goal>validate</goal> <goal>validate</goal>
</goals> </goals>
<phase>validate</phase>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
<version>${maven-checkstyle.version}</version> <version>3.1.2</version>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.puppycrawl.tools</groupId> <groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId> <artifactId>checkstyle</artifactId>
<version>${checkstyle.version}</version> <version>8.45.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.spring.nohttp</groupId> <groupId>io.spring.nohttp</groupId>
@ -215,24 +148,21 @@
<executions> <executions>
<execution> <execution>
<id>nohttp-checkstyle-validation</id> <id>nohttp-checkstyle-validation</id>
<goals>
<goal>check</goal>
</goals>
<phase>validate</phase> <phase>validate</phase>
<configuration> <configuration>
<configLocation>src/checkstyle/nohttp-checkstyle.xml</configLocation> <configLocation>src/checkstyle/nohttp-checkstyle.xml</configLocation>
<suppressionsLocation>src/checkstyle/nohttp-checkstyle-suppressions.xml</suppressionsLocation>
<encoding>UTF-8</encoding>
<sourceDirectories>${basedir}</sourceDirectories> <sourceDirectories>${basedir}</sourceDirectories>
<includes>**/*</includes> <includes>**/*</includes>
<excludes>**/.git/**/*,**/.idea/**/*,**/target/**/,**/.flattened-pom.xml,**/*.class</excludes> <excludes>**/.git/**/*,**/.idea/**/*,**/target/**/,**/.flattened-pom.xml,**/*.class</excludes>
<propertyExpansion>config_loc=${basedir}/src/checkstyle/</propertyExpansion>
</configuration> </configuration>
<goals>
<goal>check</goal>
</goals>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
@ -247,8 +177,8 @@
<additionalProperties> <additionalProperties>
<encoding.source>${project.build.sourceEncoding}</encoding.source> <encoding.source>${project.build.sourceEncoding}</encoding.source>
<encoding.reporting>${project.reporting.outputEncoding}</encoding.reporting> <encoding.reporting>${project.reporting.outputEncoding}</encoding.reporting>
<java.source>${java.version}</java.source> <java.source>${maven.compiler.source}</java.source>
<java.target>${java.version}</java.target> <java.target>${maven.compiler.target}</java.target>
</additionalProperties> </additionalProperties>
</configuration> </configuration>
</execution> </execution>
@ -266,34 +196,40 @@
</execution> </execution>
<execution> <execution>
<id>report</id> <id>report</id>
<phase>prepare-package</phase>
<goals> <goals>
<goal>report</goal> <goal>report</goal>
</goals> </goals>
<phase>prepare-package</phase>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- Spring Boot Actuator displays build-related information if a git.properties file is <!-- Spring Boot Actuator displays build-related information if a git.properties
present at the classpath --> file is present at the classpath -->
<plugin> <plugin>
<groupId>io.github.git-commit-id</groupId> <groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-maven-plugin</artifactId> <artifactId>git-commit-id-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration> <configuration>
<verbose>true</verbose>
<dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties
</generateGitPropertiesFilename>
<failOnNoGitDirectory>false</failOnNoGitDirectory> <failOnNoGitDirectory>false</failOnNoGitDirectory>
<failOnUnableToExtractRepoInfo>false</failOnUnableToExtractRepoInfo> <failOnUnableToExtractRepoInfo>false</failOnUnableToExtractRepoInfo>
</configuration> </configuration>
</plugin> </plugin>
<!-- Spring Boot Actuator displays sbom-related information if a CycloneDX SBOM file is
present at the classpath -->
<plugin>
<?m2e ignore?>
<groupId>org.cyclonedx</groupId>
<artifactId>cyclonedx-maven-plugin</artifactId>
</plugin>
</plugins> </plugins>
</build> </build>
<licenses> <licenses>
<license> <license>
<name>Apache License, Version 2.0</name> <name>Apache License, Version 2.0</name>
@ -303,38 +239,39 @@
<repositories> <repositories>
<repository> <repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<name>Spring Snapshots</name> <name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url> <url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository> </repository>
<repository> <repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>spring-milestones</id> <id>spring-milestones</id>
<name>Spring Milestones</name> <name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url> <url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository> </repository>
</repositories> </repositories>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<name>Spring Snapshots</name> <name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url> <url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository> </pluginRepository>
<pluginRepository> <pluginRepository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>spring-milestones</id> <id>spring-milestones</id>
<name>Spring Milestones</name> <name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url> <url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
@ -349,11 +286,11 @@
<executions> <executions>
<execution> <execution>
<id>unpack</id> <id>unpack</id>
<?m2e execute onConfiguration,onIncremental?>
<phase>generate-resources</phase>
<goals> <goals>
<goal>unpack</goal> <goal>unpack</goal>
</goals> </goals>
<?m2e execute onConfiguration,onIncremental?>
<phase>generate-resources</phase>
<configuration> <configuration>
<artifactItems> <artifactItems>
<artifactItem> <artifactItem>
@ -371,21 +308,21 @@
<plugin> <plugin>
<groupId>com.gitlab.haynes</groupId> <groupId>com.gitlab.haynes</groupId>
<artifactId>libsass-maven-plugin</artifactId> <artifactId>libsass-maven-plugin</artifactId>
<version>${libsass.version}</version> <version>0.2.26</version>
<executions>
<execution>
<phase>generate-resources</phase>
<?m2e execute onConfiguration,onIncremental?>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration> <configuration>
<inputPath>${basedir}/src/main/scss/</inputPath> <inputPath>${basedir}/src/main/scss/</inputPath>
<outputPath>${basedir}/src/main/resources/static/resources/css/</outputPath> <outputPath>${basedir}/src/main/resources/static/resources/css/</outputPath>
<includePath>${project.build.directory}/webjars/META-INF/resources/webjars/bootstrap/${webjars-bootstrap.version}/scss/</includePath> <includePath>${project.build.directory}/webjars/META-INF/resources/webjars/bootstrap/${webjars-bootstrap.version}/scss/</includePath>
</configuration> </configuration>
<executions>
<execution>
<?m2e execute onConfiguration,onIncremental?>
<goals>
<goal>compile</goal>
</goals>
<phase>generate-resources</phase>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
@ -401,11 +338,11 @@
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<!-- This plugin's configuration is used to store Eclipse m2e settings <!-- This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. --> only. It has no influence on the Maven build itself. -->
<plugin> <plugin>
<groupId>org.eclipse.m2e</groupId> <groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId> <artifactId>lifecycle-mapping</artifactId>
<version>${lifecycle-mapping}</version> <version>1.0.0</version>
<configuration> <configuration>
<lifecycleMappingMetadata> <lifecycleMappingMetadata>
<pluginExecutions> <pluginExecutions>
@ -419,7 +356,7 @@
</goals> </goals>
</pluginExecutionFilter> </pluginExecutionFilter>
<action> <action>
<ignore></ignore> <ignore />
</action> </action>
</pluginExecution> </pluginExecution>
<pluginExecution> <pluginExecution>
@ -432,7 +369,7 @@
</goals> </goals>
</pluginExecutionFilter> </pluginExecutionFilter>
<action> <action>
<ignore></ignore> <ignore />
</action> </action>
</pluginExecution> </pluginExecution>
<pluginExecution> <pluginExecution>
@ -445,7 +382,7 @@
</goals> </goals>
</pluginExecutionFilter> </pluginExecutionFilter>
<action> <action>
<ignore></ignore> <ignore />
</action> </action>
</pluginExecution> </pluginExecution>
</pluginExecutions> </pluginExecutions>
@ -457,4 +394,5 @@
</build> </build>
</profile> </profile>
</profiles> </profiles>
</project> </project>

158
readme.md Normal file
View file

@ -0,0 +1,158 @@
# 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)
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/spring-projects/spring-petclinic)
## Understanding the Spring Petclinic application with a few diagrams
<a href="https://speakerdeck.com/michaelisvy/spring-petclinic-sample-application">See the presentation here</a>
## Running petclinic locally
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 11 or newer):
```
git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
./mvnw package
java -jar target/*.jar
```
You can then access petclinic here: http://localhost:8080/
<img width="1042" alt="petclinic-screenshot" src="https://cloud.githubusercontent.com/assets/838318/19727082/2aee6d6c-9b8e-11e6-81fe-e889a5ddfded.png">
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):
```
./mvnw spring-boot:run
```
> NOTE: Windows users should set `git config core.autocrlf true` to avoid format assertions failing the build (use `--global` to set that flag globally).
> NOTE: If you prefer to use Gradle, you can build the app using `./gradlew build` and look for the jar file in `build/libs`.
## Building a Container
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:
```
./mvnw spring-boot:build-image
```
## In case you find a bug/suggested improvement for Spring Petclinic
Our issue tracker is available here: https://github.com/spring-projects/spring-petclinic/issues
## Database configuration
In its default configuration, Petclinic uses an in-memory database (H2) which
gets populated at startup with data. The h2 console is automatically exposed at `http://localhost:8080/h2-console`
and it is possible to inspect the content of the database using the `jdbc:h2:mem:testdb` url.
A similar setup is provided for MySQL and PostgreSQL in case a persistent database configuration is needed. Note that whenever the database type is changed, the app needs to be run with a different profile: `spring.profiles.active=mysql` for MySQL or `spring.profiles.active=postgres` for PostgreSQL.
You could start MySQL or PostgreSQL locally with whatever installer works for your OS, or with docker:
```
docker run -e MYSQL_USER=petclinic -e MYSQL_PASSWORD=petclinic -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:5.7.8
```
or
```
docker run -e POSTGRES_USER=petclinic -e POSTGRES_PASSWORD=petclinic -e POSTGRES_DB=petclinic -p 5432:5432 postgres:14.1
```
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)
and for [PostgreSQL](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources/db/postgres/petclinic_db_setup_postgres.txt).
## Compiling the CSS
There is a `petclinic.css` in `src/main/resources/static/resources/css`. It was generated from the `petclinic.scss` source, combined with the [Bootstrap](https://getbootstrap.com/) library. If you make changes to the `scss`, or upgrade Bootstrap, you will need to re-compile the CSS resources using the Maven profile "css", i.e. `./mvnw package -P css`. There is no build profile for Gradle to compile the CSS.
## Working with Petclinic in your IDE
### Prerequisites
The following items should be installed in your system:
* Java 11 or newer (full JDK not a JRE).
* git command line tool (https://help.github.com/articles/set-up-git)
* Your preferred IDE
* Eclipse with the m2e plugin. Note: when m2e is available, there is an m2 icon in `Help -> About` dialog. If m2e is
not there, just follow the install process here: https://www.eclipse.org/m2e/
* [Spring Tools Suite](https://spring.io/tools) (STS)
* IntelliJ IDEA
* [VS Code](https://code.visualstudio.com)
### Steps:
1) On the command line
```
git clone https://github.com/spring-projects/spring-petclinic.git
```
2) Inside Eclipse or STS
```
File -> Import -> Maven -> Existing Maven project
```
Then either build on the command line `./mvnw generate-resources` or using the Eclipse launcher (right click on project and `Run As -> Maven install`) to generate the css. Run the application main method by right clicking on it and choosing `Run As -> Java Application`.
3) Inside IntelliJ IDEA
In the main menu, choose `File -> Open` and select the Petclinic [pom.xml](pom.xml). Click on the `Open` button.
CSS files are generated from the Maven build. You can either build them on the command line `./mvnw generate-resources` or right click on the `spring-petclinic` project then `Maven -> Generates sources and Update Folders`.
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'`.
4) Navigate to Petclinic
Visit [http://localhost:8080](http://localhost:8080) in your browser.
## Looking for something in particular?
|Spring Boot Configuration | Class or Java property files |
|--------------------------|---|
|The Main Class | [PetClinicApplication](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java) |
|Properties Files | [application.properties](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/resources) |
|Caching | [CacheConfiguration](https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java) |
## Interesting Spring Petclinic branches and forks
The Spring Petclinic "main" branch in the [spring-projects](https://github.com/spring-projects/spring-petclinic)
GitHub org is the "canonical" implementation, currently based on Spring Boot and Thymeleaf. There are
[quite a few forks](https://spring-petclinic.github.io/docs/forks.html) in a special GitHub org
[spring-petclinic](https://github.com/spring-petclinic). If you have a special interest in a different technology stack
that could be used to implement the Pet Clinic then please join the community there.
## Interaction with other open source projects
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 some 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.
Here is a list of them:
| Name | Issue |
|------|-------|
| 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) |
| 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) |
| Spring Data: provide more flexibility when working with JPQL queries | [DATAJPA-292](https://jira.springsource.org/browse/DATAJPA-292) |
# Contributing
The [issue tracker](https://github.com/spring-projects/spring-petclinic/issues) is the preferred channel for bug reports, features requests and submitting pull requests.
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 <https://editorconfig.org>. If you have not previously done so, please fill out and submit the [Contributor License Agreement](https://cla.pivotal.io/sign/spring).
# License
The Spring PetClinic sample application is released under version 2.0 of the [Apache License](https://www.apache.org/licenses/LICENSE-2.0).
[spring-petclinic]: https://github.com/spring-projects/spring-petclinic
[spring-framework-petclinic]: https://github.com/spring-petclinic/spring-framework-petclinic
[spring-petclinic-angularjs]: https://github.com/spring-petclinic/spring-petclinic-angularjs
[javaconfig branch]: https://github.com/spring-petclinic/spring-framework-petclinic/tree/javaconfig
[spring-petclinic-angular]: https://github.com/spring-petclinic/spring-petclinic-angular
[spring-petclinic-microservices]: https://github.com/spring-petclinic/spring-petclinic-microservices
[spring-petclinic-reactjs]: https://github.com/spring-petclinic/spring-petclinic-reactjs
[spring-petclinic-graphql]: https://github.com/spring-petclinic/spring-petclinic-graphql
[spring-petclinic-kotlin]: https://github.com/spring-petclinic/spring-petclinic-kotlin
[spring-petclinic-rest]: https://github.com/spring-petclinic/spring-petclinic-rest

View file

@ -3,9 +3,9 @@
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd"> "https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions> <suppressions>
<suppress files="node_modules[\\/].*" checks=".*"/> <suppress files="node_modules/.*" checks=".*"/>
<suppress files="node[\\/].*" checks=".*"/> <suppress files="node/.*" checks=".*"/>
<suppress files="build[\\/].*" checks=".*"/> <suppress files="build/.*" checks=".*"/>
<suppress files="target[\\/].*" checks=".*"/> <suppress files="[\\/]build.log" checks="NoHttp"/>
<suppress files=".+\.(jar|git|ico|p12|gif|jks|jpg|svg|log)" checks="NoHttp"/> <suppress files=".+\.(jar|git|ico|p12|gif|jks|jpg|svg)" checks="NoHttp"/>
</suppressions> </suppressions>

View file

@ -4,7 +4,4 @@
"https://checkstyle.org/dtds/configuration_1_2.dtd"> "https://checkstyle.org/dtds/configuration_1_2.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker"> <module name="com.puppycrawl.tools.checkstyle.Checker">
<module name="io.spring.nohttp.checkstyle.check.NoHttpCheck"/> <module name="io.spring.nohttp.checkstyle.check.NoHttpCheck"/>
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/nohttp-checkstyle-suppressions.xml"/>
</module>
</module> </module>

View file

@ -18,20 +18,13 @@ package org.springframework.samples.petclinic;
import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Person;
import org.springframework.samples.petclinic.vet.Vet;
public class PetClinicRuntimeHints implements RuntimeHintsRegistrar { public class PetClinicRuntimeHints implements RuntimeHintsRegistrar {
@Override @Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) { public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources().registerPattern("db/*"); // https://github.com/spring-projects/spring-boot/issues/32654 hints.resources().registerPattern("db/*"); // https://github.com/spring-projects/spring-boot/issues/32654
hints.resources().registerPattern("messages/*"); hints.resources().registerPattern("META-INF/resources/webjars/*");
hints.resources().registerPattern("mysql-default-conf");
hints.serialization().registerType(BaseEntity.class);
hints.serialization().registerType(Person.class);
hints.serialization().registerType(Vet.class);
} }
} }

View file

@ -17,7 +17,6 @@ package org.springframework.samples.petclinic.model;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass; import jakarta.persistence.MappedSuperclass;
import jakarta.validation.constraints.NotBlank;
/** /**
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>. Used as * Simple JavaBean domain object adds a name property to <code>BaseEntity</code>. Used as
@ -25,13 +24,11 @@ import jakarta.validation.constraints.NotBlank;
* *
* @author Ken Krebs * @author Ken Krebs
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Wick Dynex
*/ */
@MappedSuperclass @MappedSuperclass
public class NamedEntity extends BaseEntity { public class NamedEntity extends BaseEntity {
@Column(name = "name") @Column(name = "name")
@NotBlank
private String name; private String name;
public String getName() { public String getName() {

View file

@ -17,7 +17,7 @@ package org.springframework.samples.petclinic.model;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass; import jakarta.persistence.MappedSuperclass;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty;
/** /**
* Simple JavaBean domain object representing an person. * Simple JavaBean domain object representing an person.
@ -28,11 +28,11 @@ import jakarta.validation.constraints.NotBlank;
public class Person extends BaseEntity { public class Person extends BaseEntity {
@Column(name = "first_name") @Column(name = "first_name")
@NotBlank @NotEmpty
private String firstName; private String firstName;
@Column(name = "last_name") @Column(name = "last_name")
@NotBlank @NotEmpty
private String lastName; private String lastName;
public String getFirstName() { public String getFirstName() {

View file

@ -30,8 +30,8 @@ import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy; import jakarta.persistence.OrderBy;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Digits;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty;
/** /**
* Simple JavaBean domain object representing an owner. * Simple JavaBean domain object representing an owner.
@ -41,29 +41,28 @@ import jakarta.validation.constraints.NotBlank;
* @author Sam Brannen * @author Sam Brannen
* @author Michael Isvy * @author Michael Isvy
* @author Oliver Drotbohm * @author Oliver Drotbohm
* @author Wick Dynex
*/ */
@Entity @Entity
@Table(name = "owners") @Table(name = "owners")
public class Owner extends Person { public class Owner extends Person {
@Column(name = "address") @Column(name = "address")
@NotBlank @NotEmpty
private String address; private String address;
@Column(name = "city") @Column(name = "city")
@NotBlank @NotEmpty
private String city; private String city;
@Column(name = "telephone") @Column(name = "telephone")
@NotBlank @NotEmpty
@Pattern(regexp = "\\d{10}", message = "Telephone must be a 10-digit number") @Digits(fraction = 0, integer = 10)
private String telephone; private String telephone;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id") @JoinColumn(name = "owner_id")
@OrderBy("name") @OrderBy("name")
private final List<Pet> pets = new ArrayList<>(); private List<Pet> pets = new ArrayList<>();
public String getAddress() { public String getAddress() {
return this.address; return this.address;
@ -102,7 +101,7 @@ public class Owner extends Person {
/** /**
* Return the Pet with the given name, or null if none found for this Owner. * Return the Pet with the given name, or null if none found for this Owner.
* @param name to test * @param name to test
* @return the Pet with the given name, or null if no such Pet exists for this Owner * @return a pet if pet name is already in use
*/ */
public Pet getPet(String name) { public Pet getPet(String name) {
return getPet(name, false); return getPet(name, false);
@ -110,8 +109,8 @@ public class Owner extends Person {
/** /**
* Return the Pet with the given id, or null if none found for this Owner. * Return the Pet with the given id, or null if none found for this Owner.
* @param id to test * @param name to test
* @return the Pet with the given id, or null if no such Pet exists for this Owner * @return a pet if pet id is already in use
*/ */
public Pet getPet(Integer id) { public Pet getPet(Integer id) {
for (Pet pet : getPets()) { for (Pet pet : getPets()) {
@ -128,14 +127,15 @@ public class Owner extends Person {
/** /**
* Return the Pet with the given name, or null if none found for this Owner. * Return the Pet with the given name, or null if none found for this Owner.
* @param name to test * @param name to test
* @param ignoreNew whether to ignore new pets (pets that are not saved yet) * @return a pet if pet name is already in use
* @return the Pet with the given name, or null if no such Pet exists for this Owner
*/ */
public Pet getPet(String name, boolean ignoreNew) { public Pet getPet(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Pet pet : getPets()) { for (Pet pet : getPets()) {
String compName = pet.getName(); if (!ignoreNew || !pet.isNew()) {
if (compName != null && compName.equalsIgnoreCase(name)) { String compName = pet.getName();
if (!ignoreNew || !pet.isNew()) { compName = compName == null ? "" : compName.toLowerCase();
if (compName.equals(name)) {
return pet; return pet;
} }
} }
@ -145,14 +145,10 @@ public class Owner extends Person {
@Override @Override
public String toString() { public String toString() {
return new ToStringCreator(this).append("id", this.getId()) return new ToStringCreator(this).append("id", this.getId()).append("new", this.isNew())
.append("new", this.isNew()) .append("lastName", this.getLastName()).append("firstName", this.getFirstName())
.append("lastName", this.getLastName()) .append("address", this.address).append("city", this.city).append("telephone", this.telephone)
.append("firstName", this.getFirstName()) .toString();
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
} }
/** /**
@ -160,7 +156,7 @@ public class Owner extends Person {
* @param petId the identifier of the {@link Pet}, must not be {@literal null}. * @param petId the identifier of the {@link Pet}, must not be {@literal null}.
* @param visit the visit to add, must not be {@literal null}. * @param visit the visit to add, must not be {@literal null}.
*/ */
public void addVisit(Integer petId, Visit visit) { public Owner addVisit(Integer petId, Visit visit) {
Assert.notNull(petId, "Pet identifier must not be null!"); Assert.notNull(petId, "Pet identifier must not be null!");
Assert.notNull(visit, "Visit must not be null!"); Assert.notNull(visit, "Visit must not be null!");
@ -170,6 +166,8 @@ public class Owner extends Person {
Assert.notNull(pet, "Invalid Pet identifier!"); Assert.notNull(pet, "Invalid Pet identifier!");
pet.addVisit(visit); pet.addVisit(visit);
return this;
} }
} }

View file

@ -16,7 +16,7 @@
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Map;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
@ -34,14 +34,12 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Ken Krebs * @author Ken Krebs
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Michael Isvy * @author Michael Isvy
* @author Wick Dynex
*/ */
@Controller @Controller
class OwnerController { class OwnerController {
@ -50,8 +48,8 @@ class OwnerController {
private final OwnerRepository owners; private final OwnerRepository owners;
public OwnerController(OwnerRepository owners) { public OwnerController(OwnerRepository clinicService) {
this.owners = owners; this.owners = clinicService;
} }
@InitBinder @InitBinder
@ -61,31 +59,29 @@ class OwnerController {
@ModelAttribute("owner") @ModelAttribute("owner")
public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) { public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) {
return ownerId == null ? new Owner() return ownerId == null ? new Owner() : this.owners.findById(ownerId);
: this.owners.findById(ownerId)
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId
+ ". Please ensure the ID is correct " + "and the owner exists in the database."));
} }
@GetMapping("/owners/new") @GetMapping("/owners/new")
public String initCreationForm() { public String initCreationForm(Map<String, Object> model) {
Owner owner = new Owner();
model.put("owner", owner);
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
} }
@PostMapping("/owners/new") @PostMapping("/owners/new")
public String processCreationForm(@Valid Owner owner, BindingResult result, RedirectAttributes redirectAttributes) { public String processCreationForm(@Valid Owner owner, BindingResult result) {
if (result.hasErrors()) { if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("error", "There was an error in creating the owner.");
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
} }
this.owners.save(owner); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "New Owner Created");
return "redirect:/owners/" + owner.getId(); return "redirect:/owners/" + owner.getId();
} }
@GetMapping("/owners/find") @GetMapping("/owners/find")
public String initFindForm() { public String initFindForm(Map<String, Object> model) {
model.put("owner", new Owner());
return "owners/findOwners"; return "owners/findOwners";
} }
@ -116,6 +112,7 @@ class OwnerController {
} }
private String addPaginationModel(int page, Model model, Page<Owner> paginated) { private String addPaginationModel(int page, Model model, Page<Owner> paginated) {
model.addAttribute("listOwners", paginated);
List<Owner> listOwners = paginated.getContent(); List<Owner> listOwners = paginated.getContent();
model.addAttribute("currentPage", page); model.addAttribute("currentPage", page);
model.addAttribute("totalPages", paginated.getTotalPages()); model.addAttribute("totalPages", paginated.getTotalPages());
@ -127,31 +124,25 @@ class OwnerController {
private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) { private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) {
int pageSize = 5; int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize); Pageable pageable = PageRequest.of(page - 1, pageSize);
return owners.findByLastNameStartingWith(lastname, pageable); return owners.findByLastName(lastname, pageable);
} }
@GetMapping("/owners/{ownerId}/edit") @GetMapping("/owners/{ownerId}/edit")
public String initUpdateOwnerForm() { public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
Owner owner = this.owners.findById(ownerId);
model.addAttribute(owner);
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
} }
@PostMapping("/owners/{ownerId}/edit") @PostMapping("/owners/{ownerId}/edit")
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId, public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result,
RedirectAttributes redirectAttributes) { @PathVariable("ownerId") int ownerId) {
if (result.hasErrors()) { if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("error", "There was an error in updating the owner.");
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
} }
if (owner.getId() != ownerId) {
result.rejectValue("id", "mismatch", "The owner ID in the form does not match the URL.");
redirectAttributes.addFlashAttribute("error", "Owner ID mismatch. Please try again.");
return "redirect:/owners/{ownerId}/edit";
}
owner.setId(ownerId); owner.setId(ownerId);
this.owners.save(owner); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Owner Values Updated");
return "redirect:/owners/{ownerId}"; return "redirect:/owners/{ownerId}";
} }
@ -163,9 +154,7 @@ class OwnerController {
@GetMapping("/owners/{ownerId}") @GetMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails"); ModelAndView mav = new ModelAndView("owners/ownerDetails");
Optional<Owner> optionalOwner = this.owners.findById(ownerId); Owner owner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
mav.addObject(owner); mav.addObject(owner);
return mav; return mav;
} }

View file

@ -16,13 +16,12 @@
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import java.util.List; import java.util.List;
import java.util.Optional;
import jakarta.annotation.Nonnull;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
/** /**
@ -35,15 +34,15 @@ import org.springframework.transaction.annotation.Transactional;
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Sam Brannen * @author Sam Brannen
* @author Michael Isvy * @author Michael Isvy
* @author Wick Dynex
*/ */
public interface OwnerRepository extends JpaRepository<Owner, Integer> { public interface OwnerRepository extends Repository<Owner, Integer> {
/** /**
* Retrieve all {@link PetType}s from the data store. * Retrieve all {@link PetType}s from the data store.
* @return a Collection of {@link PetType}s. * @return a Collection of {@link PetType}s.
*/ */
@Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
@Transactional(readOnly = true)
List<PetType> findPetTypes(); List<PetType> findPetTypes();
/** /**
@ -53,26 +52,31 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
* @return a Collection of matching {@link Owner}s (or an empty Collection if none * @return a Collection of matching {@link Owner}s (or an empty Collection if none
* found) * found)
*/ */
Page<Owner> findByLastNameStartingWith(String lastName, Pageable pageable);
@Query("SELECT DISTINCT owner FROM Owner owner left join owner.pets WHERE owner.lastName LIKE :lastName% ")
@Transactional(readOnly = true)
Page<Owner> findByLastName(@Param("lastName") String lastName, Pageable pageable);
/** /**
* Retrieve an {@link Owner} from the data store by id. * Retrieve an {@link Owner} from the data store by id.
* <p>
* This method returns an {@link Optional} containing the {@link Owner} if found. If
* no {@link Owner} is found with the provided id, it will return an empty
* {@link Optional}.
* </p>
* @param id the id to search for * @param id the id to search for
* @return an {@link Optional} containing the {@link Owner} if found, or an empty * @return the {@link Owner} if found
* {@link Optional} if not found.
* @throws IllegalArgumentException if the id is null (assuming null is not a valid
* input for id)
*/ */
Optional<Owner> findById(@Nonnull Integer id); @Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id")
@Transactional(readOnly = true)
Owner findById(@Param("id") Integer id);
/** /**
* Returns all the owners from data store * Save an {@link Owner} to the data store, either inserting or updating it.
* @param owner the {@link Owner} to save
*/
void save(Owner owner);
/**
* Returnes all the owners from data store
**/ **/
@Query("SELECT owner FROM Owner owner")
@Transactional(readOnly = true)
Page<Owner> findAll(Pageable pageable); Page<Owner> findAll(Pageable pageable);
} }

View file

@ -39,7 +39,6 @@ import jakarta.persistence.Table;
* @author Ken Krebs * @author Ken Krebs
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Sam Brannen * @author Sam Brannen
* @author Wick Dynex
*/ */
@Entity @Entity
@Table(name = "pets") @Table(name = "pets")
@ -56,7 +55,7 @@ public class Pet extends NamedEntity {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "pet_id") @JoinColumn(name = "pet_id")
@OrderBy("visit_date ASC") @OrderBy("visit_date ASC")
private final Set<Visit> visits = new LinkedHashSet<>(); private Set<Visit> visits = new LinkedHashSet<>();
public void setBirthDate(LocalDate birthDate) { public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate; this.birthDate = birthDate;

View file

@ -15,9 +15,7 @@
*/ */
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import java.time.LocalDate;
import java.util.Collection; import java.util.Collection;
import java.util.Optional;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
@ -32,13 +30,11 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Ken Krebs * @author Ken Krebs
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Wick Dynex
*/ */
@Controller @Controller
@RequestMapping("/owners/{ownerId}") @RequestMapping("/owners/{ownerId}")
@ -59,24 +55,13 @@ class PetController {
@ModelAttribute("owner") @ModelAttribute("owner")
public Owner findOwner(@PathVariable("ownerId") int ownerId) { public Owner findOwner(@PathVariable("ownerId") int ownerId) {
Optional<Owner> optionalOwner = this.owners.findById(ownerId); return this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
return owner;
} }
@ModelAttribute("pet") @ModelAttribute("pet")
public Pet findPet(@PathVariable("ownerId") int ownerId, public Pet findPet(@PathVariable("ownerId") int ownerId,
@PathVariable(name = "petId", required = false) Integer petId) { @PathVariable(name = "petId", required = false) Integer petId) {
return petId == null ? new Pet() : this.owners.findById(ownerId).getPet(petId);
if (petId == null) {
return new Pet();
}
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
return owner.getPet(petId);
} }
@InitBinder("owner") @InitBinder("owner")
@ -93,62 +78,42 @@ class PetController {
public String initCreationForm(Owner owner, ModelMap model) { public String initCreationForm(Owner owner, ModelMap model) {
Pet pet = new Pet(); Pet pet = new Pet();
owner.addPet(pet); owner.addPet(pet);
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM; return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
} }
@PostMapping("/pets/new") @PostMapping("/pets/new")
public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) {
RedirectAttributes redirectAttributes) { if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null) {
if (StringUtils.hasText(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null)
result.rejectValue("name", "duplicate", "already exists"); result.rejectValue("name", "duplicate", "already exists");
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
} }
owner.addPet(pet); owner.addPet(pet);
if (result.hasErrors()) {
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
this.owners.save(owner); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "New Pet has been Added");
return "redirect:/owners/{ownerId}"; return "redirect:/owners/{ownerId}";
} }
@GetMapping("/pets/{petId}/edit") @GetMapping("/pets/{petId}/edit")
public String initUpdateForm() { public String initUpdateForm(Owner owner, @PathVariable("petId") int petId, ModelMap model) {
Pet pet = owner.getPet(petId);
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM; return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
} }
@PostMapping("/pets/{petId}/edit") @PostMapping("/pets/{petId}/edit")
public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult result, public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) {
RedirectAttributes redirectAttributes) {
String petName = pet.getName();
// checking if the pet name already exist for the owner
if (StringUtils.hasText(petName)) {
Pet existingPet = owner.getPet(petName, false);
if (existingPet != null && !existingPet.getId().equals(pet.getId())) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) { if (result.hasErrors()) {
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM; return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
} }
owner.addPet(pet); owner.addPet(pet);
this.owners.save(owner); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Pet details has been edited");
return "redirect:/owners/{ownerId}"; return "redirect:/owners/{ownerId}";
} }

View file

@ -38,7 +38,7 @@ public class PetValidator implements Validator {
Pet pet = (Pet) obj; Pet pet = (Pet) obj;
String name = pet.getName(); String name = pet.getName();
// name validation // name validation
if (!StringUtils.hasText(name)) { if (!StringUtils.hasLength(name)) {
errors.rejectValue("name", REQUIRED, REQUIRED); errors.rejectValue("name", REQUIRED, REQUIRED);
} }

View file

@ -23,7 +23,7 @@ import org.springframework.samples.petclinic.model.BaseEntity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty;
/** /**
* Simple JavaBean domain object representing a visit. * Simple JavaBean domain object representing a visit.
@ -39,7 +39,7 @@ public class Visit extends BaseEntity {
@DateTimeFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date; private LocalDate date;
@NotBlank @NotEmpty
private String description; private String description;
/** /**

View file

@ -16,7 +16,6 @@
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -28,7 +27,6 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -36,7 +34,6 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Michael Isvy * @author Michael Isvy
* @author Dave Syer * @author Dave Syer
* @author Wick Dynex
*/ */
@Controller @Controller
class VisitController { class VisitController {
@ -62,9 +59,7 @@ class VisitController {
@ModelAttribute("visit") @ModelAttribute("visit")
public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId, public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId,
Map<String, Object> model) { Map<String, Object> model) {
Optional<Owner> optionalOwner = owners.findById(ownerId); Owner owner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
Pet pet = owner.getPet(petId); Pet pet = owner.getPet(petId);
model.put("pet", pet); model.put("pet", pet);
@ -86,14 +81,13 @@ class VisitController {
// called // called
@PostMapping("/owners/{ownerId}/pets/{petId}/visits/new") @PostMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit, public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit,
BindingResult result, RedirectAttributes redirectAttributes) { BindingResult result) {
if (result.hasErrors()) { if (result.hasErrors()) {
return "pets/createOrUpdateVisitForm"; return "pets/createOrUpdateVisitForm";
} }
owner.addVisit(petId, visit); owner.addVisit(petId, visit);
this.owners.save(owner); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Your visit has been booked");
return "redirect:/owners/{ownerId}"; return "redirect:/owners/{ownerId}";
} }

View file

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

View file

@ -37,8 +37,8 @@ class VetController {
private final VetRepository vetRepository; private final VetRepository vetRepository;
public VetController(VetRepository vetRepository) { public VetController(VetRepository clinicService) {
this.vetRepository = vetRepository; this.vetRepository = clinicService;
} }
@GetMapping("/vets.html") @GetMapping("/vets.html")
@ -49,6 +49,7 @@ class VetController {
Page<Vet> paginated = findPaginated(page); Page<Vet> paginated = findPaginated(page);
vets.getVetList().addAll(paginated.toList()); vets.getVetList().addAll(paginated.toList());
return addPaginationModel(page, paginated, model); return addPaginationModel(page, paginated, model);
} }
private String addPaginationModel(int page, Page<Vet> paginated, Model model) { private String addPaginationModel(int page, Page<Vet> paginated, Model model) {

View file

@ -8,7 +8,7 @@ spring.thymeleaf.mode=HTML
# JPA # JPA
spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false spring.jpa.open-in-view=true
# Internationalization # Internationalization
spring.messages.basename=messages/messages spring.messages.basename=messages/messages

View file

@ -15,12 +15,12 @@ INSERT INTO vet_specialties VALUES (3, 3) ON CONFLICT (vet_id, specialty_id) DO
INSERT INTO vet_specialties VALUES (4, 2) ON CONFLICT (vet_id, specialty_id) DO NOTHING; INSERT INTO vet_specialties VALUES (4, 2) ON CONFLICT (vet_id, specialty_id) DO NOTHING;
INSERT INTO vet_specialties VALUES (5, 1) ON CONFLICT (vet_id, specialty_id) DO NOTHING; INSERT INTO vet_specialties VALUES (5, 1) ON CONFLICT (vet_id, specialty_id) DO NOTHING;
INSERT INTO types (name) SELECT 'cat' WHERE NOT EXISTS (SELECT * FROM types WHERE name='cat'); INSERT INTO types (name) SELECT 'cat' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='cat');
INSERT INTO types (name) SELECT 'dog' WHERE NOT EXISTS (SELECT * FROM types WHERE name='dog'); INSERT INTO types (name) SELECT 'dog' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='dog');
INSERT INTO types (name) SELECT 'lizard' WHERE NOT EXISTS (SELECT * FROM types WHERE name='lizard'); INSERT INTO types (name) SELECT 'lizard' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='lizard');
INSERT INTO types (name) SELECT 'snake' WHERE NOT EXISTS (SELECT * FROM types WHERE name='snake'); INSERT INTO types (name) SELECT 'snake' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='snake');
INSERT INTO types (name) SELECT 'bird' WHERE NOT EXISTS (SELECT * FROM types WHERE name='bird'); INSERT INTO types (name) SELECT 'bird' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='bird');
INSERT INTO types (name) SELECT 'hamster' WHERE NOT EXISTS (SELECT * FROM types WHERE name='hamster'); INSERT INTO types (name) SELECT 'hamster' WHERE NOT EXISTS (SELECT * FROM specialties WHERE name='cat');
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); 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);
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); 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);

View file

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

View file

@ -6,4 +6,3 @@ nonNumeric=Sólo debe contener numeros
duplicateFormSubmission=No se permite el envío de formularios duplicados duplicateFormSubmission=No se permite el envío de formularios duplicados
typeMismatch.date=Fecha invalida typeMismatch.date=Fecha invalida
typeMismatch.birthDate=Fecha invalida typeMismatch.birthDate=Fecha invalida

View file

@ -1,9 +0,0 @@
welcome=خوش آمدید
required=الزامی
notFound=یافت نشد
duplicate=قبلا استفاده شده
nonNumeric=باید عددی باشد
duplicateFormSubmission=ارسال تکراری فرم مجاز نیست
typeMismatch.date=تاریخ نامعتبر
typeMismatch.birthDate=تاریخ تولد نامعتبر

View file

@ -1,8 +0,0 @@
welcome=환영합니다
required=입력이 필요합니다
notFound=찾을 수 없습니다
duplicate=이미 존재합니다
nonNumeric=모두 숫자로 입력해야 합니다
duplicateFormSubmission=중복 제출은 허용되지 않습니다
typeMismatch.date=잘못된 날짜입니다
typeMismatch.birthDate=잘못된 날짜입니다

View file

@ -1,8 +0,0 @@
welcome=Bem-vindo
required=E necessario
notFound=Nao foi encontrado
duplicate=Ja esta em uso
nonNumeric=Deve ser tudo numerico
duplicateFormSubmission=O envio duplicado de formulario nao e permitido
typeMismatch.date=Data invalida
typeMismatch.birthDate=Data de nascimento invalida

View file

@ -1,9 +0,0 @@
welcome=Добро пожаловать
required=необходимо
notFound=не найдено
duplicate=уже используется
nonNumeric=должно быть все числовое значение
duplicateFormSubmission=Дублирование формы не допускается
typeMismatch.date=неправильная даные
typeMismatch.birthDate=неправильная дата

View file

@ -1,9 +0,0 @@
welcome=hoş geldiniz
required=gerekli
notFound=bulunamadı
duplicate=zaten kullanılıyor
nonNumeric=sadece sayısal olmalıdır
duplicateFormSubmission=Formun tekrar gönderilmesine izin verilmez
typeMismatch.date=geçersiz tarih
typeMismatch.birthDate=geçersiz tarih

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

View file

@ -1,66 +0,0 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 2674.9 417">
<style>
.st0, .st1 {
fill: #6db33f;
}
.st3 {
fill: #fff;
}
</style>
<g>
<path class="st0"
d="M366.9,29c-5.8,14.1-13.3,26.6-21.6,37.8c-36.6-37.3-87.8-61-144.3-61C90,5.8-0.7,96-0.7,207.4 c0,58.2,24.9,110.6,64.4,147.6l7.5,6.7c34.9,29.5,80.3,47.4,129.7,47.4c106,0,193.3-82.7,200.8-187.1 C407.7,171.3,392.3,106.4,366.9,29z M92.9,356.7c-5.8,7.5-16.6,8.3-24.1,2.5s-8.3-16.6-2.5-24.1s16.6-8.3,24.1-2.5 C97.5,338.4,98.7,349.2,92.9,356.7z M365.7,296.4c-49.5,66.1-155.9,43.7-223.7,47c0,0-12.1,0.8-24.1,2.5c0,0,4.6-2.1,10.4-4.2 c47.8-16.6,70.3-20,99.4-34.9c54.5-27.9,108.9-89,119.8-152.2c-20.8,60.7-84,113.1-141.4,134.3c-39.5,14.6-110.6,28.7-110.6,28.7 l-2.9-1.7c-48.2-23.7-49.9-128.5,38.3-162.2c38.7-15,75.3-6.7,117.3-16.6c44.5-10.4,96.1-43.7,116.8-87.3 C388.1,120.1,416.4,229,365.7,296.4z"></path>
<g>
<path class="st1"
d="M516.2,286.4c-5-2.5-8.3-8.3-8.3-15.4c0-10,7.9-18.3,18.3-18.3c3.7,0,7.1,1.2,9.6,2.5 c18.7,12.5,38.7,18.7,56.1,18.7c19.1,0,30.4-8.3,30.4-21.2v-0.8c0-15.4-20.8-20.4-43.7-27.4c-28.7-8.3-61.1-20-61.1-57.4v-0.8 c0-37,30.8-59.5,69.4-59.5c20.8,0,42.4,5.8,61.5,15.8c6.2,3.3,10.8,9.1,10.8,17c0,10.4-8.3,18.3-18.7,18.3c-3.7,0-5.8-0.8-8.7-2.1 c-15.8-8.3-32-13.3-45.7-13.3c-17.5,0-27.4,8.3-27.4,19.1v0.8c0,14.6,21.2,20.4,44.1,27.9c28.7,8.7,60.7,22,60.7,57v0.8 c0,41.2-32,61.5-72.3,61.5C565.7,309.7,538.6,301.8,516.2,286.4z"></path>
<path class="st1"
d="M680,129.7c0-12.5,9.6-22.5,22-22.5s22.5,10,22.5,22.5V143c14.6-20.4,34.9-36.6,66.5-36.6 c45.7,0,90.6,36.2,90.6,101.5v0.8c0,64.9-44.5,101.5-90.6,101.5c-32.4,0-52.8-16.2-66.5-34.5v69c0,12.5-10,22.5-22.5,22.5 c-12.1,0-22-9.6-22-22.5V129.7z M836.8,208.7v-0.8c0-37.8-25.4-62.4-55.7-62.4c-30.4,0-57,25.4-57,62.4v0.8 c0,37.4,26.6,62.4,57,62.4C811.4,271.5,836.8,247.3,836.8,208.7z"></path>
<path class="st1"
d="M899.1,129.7c0-12.5,9.6-22.5,22-22.5s22.5,10,22.5,22.5v10.8c2.1-16.6,29.5-33.3,49.1-33.3 c14.1,0,22,9.1,22,22c0,11.6-7.9,19.5-17.9,21.6c-32,5.4-53.6,33.3-53.6,71.9v64.4c0,12.1-10,22-22.5,22c-12.1,0-22-9.6-22-22 V129.7H899.1z"></path>
<path class="st1"
d="M1032.6,130.1c0-12.5,9.6-22.5,22-22.5s22.5,10,22.5,22.5v157.6c0,12.5-10,22-22.5,22c-12.1,0-22-9.6-22-22 V130.1z"></path>
<path class="st1"
d="M1100,130.1c0-12.5,9.6-22.5,22-22.5s22.5,10,22.5,22.5v9.1c12.5-18.3,30.8-32,61.1-32 c44.1,0,69.4,29.5,69.4,74.8v105.2c0,12.5-9.6,22-22,22s-22.5-9.6-22.5-22v-91.5c0-30.4-15-47.8-42-47.8 c-25.8,0-44.1,18.3-44.1,48.6v91.1c0,12.5-10,22-22.5,22c-12.1,0-22-9.6-22-22L1100,130.1L1100,130.1z"></path>
<path class="st1"
d="M1472.1,106.8c-12.5,0-22.5,10-22.5,22.5v13.3c-14.6-20.4-34.9-36.6-66.5-36.6c-45.7,0-90.6,36.2-90.6,101.5 v0.8c0,64.9,44.5,101.5,90.6,101.5c32.4,0,52.8-16.2,66.5-34.1c-2.1,35.3-23.7,53.6-61.5,53.6c-22.5,0-42-5.4-59.9-15.4 c-2.1-1.2-5-1.7-7.9-1.7c-10.4,0-19.1,8.3-19.1,18.3c0,8.7,5,15,12.5,17.9c23.7,11.6,48.2,17.5,75.7,17.5 c35.3,0,62.8-8.3,80.3-26.2c16.2-16.2,24.9-40.7,24.9-73.6V129.7C1494.6,116.8,1484.6,106.8,1472.1,106.8z M1393.5,271 c-30.8,0-55.7-24.1-55.7-62.8v-0.8c0-37.8,25.4-62.4,55.7-62.4s57,25.4,57,62.4v0.8C1450.9,245.7,1424.3,271,1393.5,271z"></path>
<path class="st1"
d="M1077.5,53.6c0,12.5-10,22.5-22.5,22.5s-22.5-10-22.5-22.5s10-22.5,22.5-22.5 C1067.1,30.7,1077.5,40.7,1077.5,53.6z"></path>
</g>
<g>
<path class="st1"
d="M1545.7,153.8c-12.5,0-22.9-10.4-22.9-22.9c0-12.9,10.4-22.9,22.9-22.9c12.9,0,22.9,10.4,22.9,22.9 S1558.6,153.8,1545.7,153.8z M1545.7,111.4c-10.8,0-19.5,8.7-19.5,19.5s8.7,19.5,19.5,19.5s19.5-8.7,19.5-19.5 C1565.2,119.7,1556.5,111.4,1545.7,111.4z M1551.9,143.8l-6.7-10.4h-4.6v10.4h-3.7v-26.2h10.8c4.6,0,8.7,3.3,8.7,7.9 c0,5.8-5.4,7.9-6.7,7.9l7.1,10.4H1551.9L1551.9,143.8z M1547.4,120.9h-6.7v9.1h7.1c2.1,0,4.6-1.7,4.6-4.6 C1552.4,122.6,1549.9,120.9,1547.4,120.9z"></path>
</g>
<g>
<path class="st1"
d="M1652.3,260.1c0,20-12.8,34.1-30,34.1c-10.4,0-18.8-5.2-23.7-13.7v12.2h-9.4v-88h9.4v35.1 c4.9-8.6,13.2-13.7,23.7-13.7C1639.4,226.1,1652.3,240.2,1652.3,260.1z M1642.3,260.1c0-15-9.1-25.6-21.8-25.6 c-12.8,0-21.9,10.6-21.9,25.6s9.1,25.7,21.9,25.7C1633.3,285.8,1642.3,275.1,1642.3,260.1z"></path>
<path class="st1"
d="M1668,313.3l2.3-8.1c2.3,1.1,4.9,1.6,7.7,1.6c4.2,0,6.9-1.4,9.4-5.8l3.8-8.1l-28.3-65.3h10.4l22.8,54.1 l21.5-54.1h10.2l-29.7,72.4c-4.5,11.1-10.8,15.2-19.8,15.4C1674.6,315.4,1671,314.6,1668,313.3z"></path>
<path class="st1"
d="M1861.3,206.2l-38.1,86.5h-10.7l-38.1-86.5h10.7l32.9,74.4l32.7-74.4L1861.3,206.2L1861.3,206.2z"></path>
<path class="st1"
d="M1877.1,206.2h9.8l32.1,60.3l32.1-60.3h9.8v86.5h-9.8v-65.3l-32.1,60.3l-32.1-60.3v65.3h-9.8V206.2z"></path>
<path class="st1"
d="M1977.2,227.6h10.1l16.2,52.5l17.8-52.5h8.2l17.8,52.5l16.2-52.5h10.1l-21.9,65.1h-8.9l-17.2-52l-17.5,52 h-8.9L1977.2,227.6z"></path>
<path class="st1"
d="M2140.1,253.1v39.7h-9.4v-10.2c-4.7,7.7-14.4,11.7-22.9,11.7c-13.7,0-23.8-7.9-23.8-20.8 c0-13,11.6-21.7,25.6-21.7c7,0,14.5,1.5,21.2,3.7v-2.4c0-8.8-3.5-18.9-17.6-18.9c-6.5,0-13.1,2.9-19,5.9l-3.8-7.7 c9.3-4.7,17.1-6.3,23.4-6.3C2131.4,226.1,2140.1,237.3,2140.1,253.1z M2130.7,272.3v-9.9c-5.9-1.6-12.6-2.6-19.6-2.6 c-9.7,0-17.9,5.5-17.9,13.3c0,8.1,7,12.8,16.2,12.8C2118,285.9,2128.2,281.5,2130.7,272.3z"></path>
<path class="st1"
d="M2194.9,226.1v8.4c-14.7,0-25.2,9.1-25.2,21.8v36.4h-9.4v-65.1h9.4v12.7 C2173.6,231.7,2182.9,226.1,2194.9,226.1z"></path>
<path class="st1"
d="M2257.8,278l5.8,6.2c-5.7,6.2-17.1,10.1-26.2,10.1c-17.4,0-33-14.2-33-34.2c0-19.4,14.6-33.9,32.1-33.9 c19.6,0,30.8,14.9,30.8,37.6H2214c1.4,12.7,10.3,22,23.2,22C2245,285.8,2253.8,282.4,2257.8,278z M2214.3,255.3h43.8 c-1.3-11.7-8.2-20.8-21.2-20.8C2225.4,234.6,2216.1,242.7,2214.3,255.3z"></path>
<path class="st1"
d="M2344.6,215.6h-29.1v-9.3h68v9.3h-29.1v77.2h-9.8L2344.6,215.6L2344.6,215.6z"></path>
<path class="st1"
d="M2451.6,253.1v39.7h-9.4v-10.2c-4.7,7.7-14.4,11.7-22.9,11.7c-13.7,0-23.8-7.9-23.8-20.8 c0-13,11.6-21.7,25.6-21.7c7,0,14.5,1.5,21.2,3.7v-2.4c0-8.8-3.5-18.9-17.6-18.9c-6.5,0-13.1,2.9-19,5.9l-3.8-7.7 c9.3-4.7,17.1-6.3,23.4-6.3C2442.9,226.1,2451.6,237.3,2451.6,253.1z M2442.2,272.3v-9.9c-5.9-1.6-12.6-2.6-19.6-2.6 c-9.7,0-17.9,5.5-17.9,13.3c0,8.1,7,12.8,16.2,12.8C2429.4,285.9,2439.6,281.5,2442.2,272.3z"></path>
<path class="st1"
d="M2526.3,251.3v41.4h-9.4v-40.2c0-10.6-6.7-18-16.2-18c-11,0-20.1,7.7-20.1,16.7v41.4h-9.4v-65.1h9.4v10.4 c3.8-6.9,12.2-12,21.4-12C2516.2,226.1,2526.3,236.6,2526.3,251.3z"></path>
<path class="st1"
d="M2542.6,285.3l38.4-48.7h-37.6v-8.9h50.4v7.4l-38.5,48.7h38.8v8.9h-51.4L2542.6,285.3L2542.6,285.3z"></path>
<path class="st1"
d="M2665.4,227.6v65.1h-9.4v-10.4c-3.8,6.9-12.2,12-21.4,12c-14.4,0-24.4-10.4-24.4-25.2v-41.4h9.4v40.2 c0,10.6,6.7,18,16.2,18c11,0,20.1-7.7,20.1-16.7v-41.4h9.5V227.6z"></path>
</g>
</g>
<path class="st3"
d="M92.9,356.7c-5.8,7.5-16.6,8.3-24.1,2.5s-8.3-16.6-2.5-24.1s16.6-8.3,24.1-2.5 C97.5,338.4,98.7,349.2,92.9,356.7z"></path>
<path class="st3"
d="M365.7,296.4c-49.5,66.1-155.9,43.7-223.7,47c0,0-12.1,0.8-24.1,2.5c0,0,4.6-2.1,10.4-4.2 c47.8-16.6,70.3-20,99.4-34.9c54.5-27.9,108.9-89,119.8-152.2c-20.8,60.7-84,113.1-141.4,134.3c-39.5,14.6-110.6,28.7-110.6,28.7 l-2.9-1.7c-48.2-23.7-49.9-128.5,38.3-162.2c38.7-15,75.3-6.7,117.3-16.6c44.5-10.4,96.1-43.7,116.8-87.3 C388.1,120.1,416.4,229,365.7,296.4z"></path>
</svg>

Before

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

8
src/main/resources/templates/fragments/layout.html Normal file → Executable file
View file

@ -17,7 +17,7 @@
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]--> <![endif]-->
<link th:href="@{/webjars/font-awesome/css/font-awesome.min.css}" rel="stylesheet"> <link th:href="@{/webjars/font-awesome/4.7.0/css/font-awesome.min.css}" rel="stylesheet">
<link rel="stylesheet" th:href="@{/resources/css/petclinic.css}" /> <link rel="stylesheet" th:href="@{/resources/css/petclinic.css}" />
</head> </head>
@ -80,14 +80,14 @@
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-12 text-center"> <div class="col-12 text-center">
<img src="../static/images/spring-logo.svg" th:src="@{/resources/images/spring-logo.svg}" alt="VMware Tanzu Logo" class="logo"> <img src="../static/resources/images/spring-pivotal-logo.png"
</div> th:src="@{/resources/images/spring-pivotal-logo.png}" alt="Sponsored by Pivotal" /></div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<script th:src="@{/webjars/bootstrap/dist/js/bootstrap.bundle.min.js}"></script> <script th:src="@{/webjars/bootstrap/5.1.3/dist/js/bootstrap.bundle.min.js}"></script>
</body> </body>

View file

@ -7,18 +7,8 @@
<h2>Owner Information</h2> <h2>Owner Information</h2>
<div th:if="${message}" class="alert alert-success" id="success-message">
<span th:text="${message}"></span>
</div>
<div th:if="${error}" class="alert alert-danger" id="error-message">
<span th:text="${error}"></span>
</div>
<table class="table table-striped" th:object="${owner}"> <table class="table table-striped" th:object="${owner}">
<tr> <tr>
<th>Name</th> <th>Name</th>
@ -83,20 +73,7 @@
</tr> </tr>
</table> </table>
<script>
// Function to hide the success and error messages after 3 seconds
function hideMessages() {
setTimeout(function() {
document.getElementById("success-message").style.display = "none";
document.getElementById("error-message").style.display = "none";
}, 3000); // 3000 milliseconds (3 seconds)
}
// Call the function to hide messages
hideMessages();
</script>
</body> </body>
</html> </html>

View file

@ -188,10 +188,6 @@ table td.action-column {
color: $spring-brown; color: $spring-brown;
} }
.logo {
width: 200px;
}
.myspinner { .myspinner {
animation-name: spinner; animation-name: spinner;
animation-duration: 2s; animation-duration: 2s;

View file

@ -1,73 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.samples.petclinic.vet.VetRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.aot.DisabledInAotMode;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("mysql")
@Testcontainers(disabledWithoutDocker = true)
@DisabledInNativeImage
@DisabledInAotMode
class MySqlIntegrationTests {
@ServiceConnection
@Container
static MySQLContainer<?> container = new MySQLContainer<>("mysql:9.1");
@LocalServerPort
int port;
@Autowired
private VetRepository vets;
@Autowired
private RestTemplateBuilder builder;
@Test
void testFindAll() {
vets.findAll();
vets.findAll(); // served from cache
}
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.testcontainers.containers.MySQLContainer;
/**
* PetClinic Spring Boot Application.
*
* @author Dave Syer
*
*/
@Configuration
public class MysqlTestApplication {
@ServiceConnection
@Profile("mysql")
@Bean
static MySQLContainer<?> container() {
return new MySQLContainer<>("mysql:9.1");
}
public static void main(String[] args) {
SpringApplication.run(PetClinicApplication.class, "--spring.profiles.active=mysql");
}
}

View file

@ -20,7 +20,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.test.web.server.LocalServerPort;
@ -32,7 +31,7 @@ import org.springframework.samples.petclinic.vet.VetRepository;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PetClinicIntegrationTests { class PetClinicIntegrationTests {
@LocalServerPort @LocalServerPort
int port; int port;
@ -44,7 +43,7 @@ public class PetClinicIntegrationTests {
private RestTemplateBuilder builder; private RestTemplateBuilder builder;
@Test @Test
void testFindAll() { void testFindAll() throws Exception {
vets.findAll(); vets.findAll();
vets.findAll(); // served from cache vets.findAll(); // served from cache
} }
@ -56,8 +55,4 @@ public class PetClinicIntegrationTests {
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
} }
public static void main(String[] args) {
SpringApplication.run(PetClinicApplication.class, args);
}
} }

View file

@ -1,150 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.samples.petclinic.vet.VetRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.DockerClientFactory;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.docker.compose.skip.in-tests=false", //
"spring.docker.compose.start.arguments=--force-recreate,--renew-anon-volumes,postgres" })
@ActiveProfiles("postgres")
@DisabledInNativeImage
public class PostgresIntegrationTests {
@LocalServerPort
int port;
@Autowired
private VetRepository vets;
@Autowired
private RestTemplateBuilder builder;
@BeforeAll
static void available() {
assumeTrue(DockerClientFactory.instance().isDockerAvailable(), "Docker not available");
}
public static void main(String[] args) {
new SpringApplicationBuilder(PetClinicApplication.class) //
.profiles("postgres") //
.properties( //
"spring.docker.compose.start.arguments=postgres" //
) //
.listeners(new PropertiesLogger()) //
.run(args);
}
@Test
void testFindAll() throws Exception {
vets.findAll();
vets.findAll(); // served from cache
}
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}
static class PropertiesLogger implements ApplicationListener<ApplicationPreparedEvent> {
private static final Log log = LogFactory.getLog(PropertiesLogger.class);
private ConfigurableEnvironment environment;
private boolean isFirstRun = true;
@Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
if (isFirstRun) {
environment = event.getApplicationContext().getEnvironment();
printProperties();
}
isFirstRun = false;
}
public void printProperties() {
for (EnumerablePropertySource<?> source : findPropertiesPropertySources()) {
log.info("PropertySource: " + source.getName());
String[] names = source.getPropertyNames();
Arrays.sort(names);
for (String name : names) {
String resolved = environment.getProperty(name);
assertNotNull(resolved, "resolved environment property: " + name + " is null.");
Object sourceProperty = source.getProperty(name);
assertNotNull(sourceProperty, "source property was expecting an object but is null.");
assertNotNull(sourceProperty.toString(), "source property toString() returned null.");
String value = sourceProperty.toString();
if (resolved.equals(value)) {
log.info(name + "=" + resolved);
}
else {
log.info(name + "=" + value + " OVERRIDDEN to " + resolved);
}
}
}
}
private List<EnumerablePropertySource<?>> findPropertiesPropertySources() {
List<EnumerablePropertySource<?>> sources = new LinkedList<>();
for (PropertySource<?> source : environment.getPropertySources()) {
if (source instanceof EnumerablePropertySource enumerable) {
sources.add(enumerable);
}
}
return sources;
}
}
}

View file

@ -53,8 +53,8 @@ class ValidatorTests {
assertThat(constraintViolations).hasSize(1); assertThat(constraintViolations).hasSize(1);
ConstraintViolation<Person> violation = constraintViolations.iterator().next(); ConstraintViolation<Person> violation = constraintViolations.iterator().next();
assertThat(violation.getPropertyPath()).hasToString("firstName"); assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
assertThat(violation.getMessage()).isEqualTo("must not be blank"); assertThat(violation.getMessage()).isEqualTo("must not be empty");
} }
} }

View file

@ -16,48 +16,43 @@
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.aot.DisabledInAotMode;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.time.LocalDate;
import java.util.Optional;
import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.time.LocalDate;
import java.util.List;
import org.assertj.core.util.Lists;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.test.web.servlet.MockMvc;
/** /**
* Test class for {@link OwnerController} * Test class for {@link OwnerController}
* *
* @author Colin But * @author Colin But
* @author Wick Dynex
*/ */
@WebMvcTest(OwnerController.class) @WebMvcTest(OwnerController.class)
@DisabledInNativeImage
@DisabledInAotMode
class OwnerControllerTests { class OwnerControllerTests {
private static final int TEST_OWNER_ID = 1; private static final int TEST_OWNER_ID = 1;
@ -65,7 +60,7 @@ class OwnerControllerTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@MockitoBean @MockBean
private OwnerRepository owners; private OwnerRepository owners;
private Owner george() { private Owner george() {
@ -85,18 +80,18 @@ class OwnerControllerTests {
george.addPet(max); george.addPet(max);
max.setId(1); max.setId(1);
return george; return george;
} };
@BeforeEach @BeforeEach
void setup() { void setup() {
Owner george = george(); Owner george = george();
given(this.owners.findByLastNameStartingWith(eq("Franklin"), any(Pageable.class))) given(this.owners.findByLastName(eq("Franklin"), any(Pageable.class)))
.willReturn(new PageImpl<>(Lists.newArrayList(george))); .willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Lists.newArrayList(george))); given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(george)); given(this.owners.findById(TEST_OWNER_ID)).willReturn(george);
Visit visit = new Visit(); Visit visit = new Visit();
visit.setDate(LocalDate.now()); visit.setDate(LocalDate.now());
george.getPet("Max").getVisits().add(visit); george.getPet("Max").getVisits().add(visit);
@ -105,149 +100,122 @@ class OwnerControllerTests {
@Test @Test
void testInitCreationForm() throws Exception { void testInitCreationForm() throws Exception {
mockMvc.perform(get("/owners/new")) mockMvc.perform(get("/owners/new")).andExpect(status().isOk()).andExpect(model().attributeExists("owner"))
.andExpect(status().isOk()) .andExpect(view().name("owners/createOrUpdateOwnerForm"));
.andExpect(model().attributeExists("owner"))
.andExpect(view().name("owners/createOrUpdateOwnerForm"));
} }
@Test @Test
void testProcessCreationFormSuccess() throws Exception { void testProcessCreationFormSuccess() throws Exception {
mockMvc mockMvc.perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs")
.perform(post("/owners/new").param("firstName", "Joe") .param("address", "123 Caramel Street").param("city", "London").param("telephone", "01316761638"))
.param("lastName", "Bloggs") .andExpect(status().is3xxRedirection());
.param("address", "123 Caramel Street")
.param("city", "London")
.param("telephone", "1316761638"))
.andExpect(status().is3xxRedirection());
} }
@Test @Test
void testProcessCreationFormHasErrors() throws Exception { void testProcessCreationFormHasErrors() throws Exception {
mockMvc mockMvc.perform(
.perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London")) post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London"))
.andExpect(status().isOk()) .andExpect(status().isOk()).andExpect(model().attributeHasErrors("owner"))
.andExpect(model().attributeHasErrors("owner")) .andExpect(model().attributeHasFieldErrors("owner", "address"))
.andExpect(model().attributeHasFieldErrors("owner", "address")) .andExpect(model().attributeHasFieldErrors("owner", "telephone"))
.andExpect(model().attributeHasFieldErrors("owner", "telephone")) .andExpect(view().name("owners/createOrUpdateOwnerForm"));
.andExpect(view().name("owners/createOrUpdateOwnerForm"));
} }
@Test @Test
void testInitFindForm() throws Exception { void testInitFindForm() throws Exception {
mockMvc.perform(get("/owners/find")) mockMvc.perform(get("/owners/find")).andExpect(status().isOk()).andExpect(model().attributeExists("owner"))
.andExpect(status().isOk()) .andExpect(view().name("owners/findOwners"));
.andExpect(model().attributeExists("owner"))
.andExpect(view().name("owners/findOwners"));
} }
@Test @Test
void testProcessFindFormSuccess() throws Exception { void testProcessFindFormSuccess() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george(), new Owner())); Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList(george(), new Owner()));
when(this.owners.findByLastNameStartingWith(anyString(), any(Pageable.class))).thenReturn(tasks); Mockito.when(this.owners.findByLastName(anyString(), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList")); mockMvc.perform(get("/owners?page=1")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList"));
} }
@Test @Test
void testProcessFindFormByLastName() throws Exception { void testProcessFindFormByLastName() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george())); Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList(george()));
when(this.owners.findByLastNameStartingWith(eq("Franklin"), any(Pageable.class))).thenReturn(tasks); Mockito.when(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin")) mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin")).andExpect(status().is3xxRedirection())
.andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID));
.andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID));
} }
@Test @Test
void testProcessFindFormNoOwnersFound() throws Exception { void testProcessFindFormNoOwnersFound() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList()); Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList());
when(this.owners.findByLastNameStartingWith(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks); Mockito.when(this.owners.findByLastName(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname")) mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname")).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("owner", "lastName"))
.andExpect(model().attributeHasFieldErrors("owner", "lastName")) .andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound"))
.andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound")) .andExpect(view().name("owners/findOwners"));
.andExpect(view().name("owners/findOwners"));
} }
@Test @Test
void testInitUpdateOwnerForm() throws Exception { void testInitUpdateOwnerForm() throws Exception {
mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)) mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(model().attributeExists("owner"))
.andExpect(model().attributeExists("owner")) .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin"))))
.andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) .andExpect(model().attribute("owner", hasProperty("firstName", is("George"))))
.andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St."))))
.andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) .andExpect(model().attribute("owner", hasProperty("city", is("Madison"))))
.andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023"))))
.andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) .andExpect(view().name("owners/createOrUpdateOwnerForm"));
.andExpect(view().name("owners/createOrUpdateOwnerForm"));
} }
@Test @Test
void testProcessUpdateOwnerFormSuccess() throws Exception { void testProcessUpdateOwnerFormSuccess() throws Exception {
mockMvc mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe")
.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") .param("lastName", "Bloggs").param("address", "123 Caramel Street").param("city", "London")
.param("lastName", "Bloggs") .param("telephone", "01616291589")).andExpect(status().is3xxRedirection())
.param("address", "123 Caramel Street") .andExpect(view().name("redirect:/owners/{ownerId}"));
.param("city", "London")
.param("telephone", "1616291589"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
} }
@Test @Test
void testProcessUpdateOwnerFormUnchangedSuccess() throws Exception { void testProcessUpdateOwnerFormUnchangedSuccess() throws Exception {
mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID)) mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID)).andExpect(status().is3xxRedirection())
.andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/{ownerId}"));
.andExpect(view().name("redirect:/owners/{ownerId}"));
} }
@Test @Test
void testProcessUpdateOwnerFormHasErrors() throws Exception { void testProcessUpdateOwnerFormHasErrors() throws Exception {
mockMvc mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe")
.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") .param("lastName", "Bloggs").param("address", "").param("telephone", "")).andExpect(status().isOk())
.param("lastName", "Bloggs") .andExpect(model().attributeHasErrors("owner"))
.param("address", "") .andExpect(model().attributeHasFieldErrors("owner", "address"))
.param("telephone", "")) .andExpect(model().attributeHasFieldErrors("owner", "telephone"))
.andExpect(status().isOk()) .andExpect(view().name("owners/createOrUpdateOwnerForm"));
.andExpect(model().attributeHasErrors("owner"))
.andExpect(model().attributeHasFieldErrors("owner", "address"))
.andExpect(model().attributeHasFieldErrors("owner", "telephone"))
.andExpect(view().name("owners/createOrUpdateOwnerForm"));
} }
@Test @Test
void testShowOwner() throws Exception { void testShowOwner() throws Exception {
mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)) mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin"))))
.andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) .andExpect(model().attribute("owner", hasProperty("firstName", is("George"))))
.andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St."))))
.andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) .andExpect(model().attribute("owner", hasProperty("city", is("Madison"))))
.andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023"))))
.andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) .andExpect(model().attribute("owner", hasProperty("pets", not(empty()))))
.andExpect(model().attribute("owner", hasProperty("pets", not(empty())))) .andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher<List<Pet>>() {
.andExpect(model().attribute("owner",
hasProperty("pets", hasItem(hasProperty("visits", hasSize(greaterThan(0)))))))
.andExpect(view().name("owners/ownerDetails"));
}
@Test @Override
public void testProcessUpdateOwnerFormWithIdMismatch() throws Exception { public boolean matches(Object item) {
int pathOwnerId = 1; @SuppressWarnings("unchecked")
List<Pet> pets = (List<Pet>) item;
Pet pet = pets.get(0);
if (pet.getVisits().isEmpty()) {
return false;
}
return true;
}
Owner owner = new Owner(); @Override
owner.setId(2); public void describeTo(Description description) {
owner.setFirstName("John"); description.appendText("Max did not have any visits");
owner.setLastName("Doe"); }
owner.setAddress("Center Street"); }))).andExpect(view().name("owners/ownerDetails"));
owner.setCity("New York");
owner.setTelephone("0123456789");
when(owners.findById(pathOwnerId)).thenReturn(Optional.of(owner));
mockMvc.perform(MockMvcRequestBuilders.post("/owners/{ownerId}/edit", pathOwnerId).flashAttr("owner", owner))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/owners/" + pathOwnerId + "/edit"))
.andExpect(flash().attributeExists("error"));
} }
} }

View file

@ -18,37 +18,26 @@ package org.springframework.samples.petclinic.owner;
import org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.FilterType;
import org.springframework.test.context.aot.DisabledInAotMode;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.Optional;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
/** /**
* Test class for the {@link PetController} * Test class for the {@link PetController}
* *
* @author Colin But * @author Colin But
* @author Wick Dynex
*/ */
@WebMvcTest(value = PetController.class, @WebMvcTest(value = PetController.class,
includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE))
@DisabledInNativeImage
@DisabledInAotMode
class PetControllerTests { class PetControllerTests {
private static final int TEST_OWNER_ID = 1; private static final int TEST_OWNER_ID = 1;
@ -58,7 +47,7 @@ class PetControllerTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@MockitoBean @MockBean
private OwnerRepository owners; private OwnerRepository owners;
@BeforeEach @BeforeEach
@ -67,142 +56,55 @@ class PetControllerTests {
cat.setId(3); cat.setId(3);
cat.setName("hamster"); cat.setName("hamster");
given(this.owners.findPetTypes()).willReturn(Lists.newArrayList(cat)); given(this.owners.findPetTypes()).willReturn(Lists.newArrayList(cat));
Owner owner = new Owner(); Owner owner = new Owner();
Pet pet = new Pet(); Pet pet = new Pet();
Pet dog = new Pet();
owner.addPet(pet); owner.addPet(pet);
owner.addPet(dog);
pet.setId(TEST_PET_ID); pet.setId(TEST_PET_ID);
dog.setId(TEST_PET_ID + 1); given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
pet.setName("petty");
dog.setName("doggy");
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(owner));
} }
@Test @Test
void testInitCreationForm() throws Exception { void testInitCreationForm() throws Exception {
mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)) mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdatePetForm")).andExpect(model().attributeExists("pet"));
.andExpect(view().name("pets/createOrUpdatePetForm"))
.andExpect(model().attributeExists("pet"));
} }
@Test @Test
void testProcessCreationFormSuccess() throws Exception { void testProcessCreationFormSuccess() throws Exception {
mockMvc mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty")
.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection())
.param("type", "hamster") .andExpect(view().name("redirect:/owners/{ownerId}"));
.param("birthDate", "2015-02-12"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
} }
@Nested @Test
class ProcessCreationFormHasErrors { void testProcessCreationFormHasErrors() throws Exception {
mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty").param("birthDate",
@Test "2015-02-12")).andExpect(model().attributeHasNoErrors("owner"))
void testProcessCreationFormWithBlankName() throws Exception { .andExpect(model().attributeHasErrors("pet")).andExpect(model().attributeHasFieldErrors("pet", "type"))
mockMvc .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")).andExpect(status().isOk())
.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "\t \n")
.param("birthDate", "2015-02-12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "name"))
.andExpect(model().attributeHasFieldErrorCode("pet", "name", "required"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdatePetForm")); .andExpect(view().name("pets/createOrUpdatePetForm"));
} }
@Test @Test
void testProcessCreationFormWithDuplicateName() throws Exception { void testInitUpdateForm() throws Exception {
mockMvc mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID))
.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "petty") .andExpect(status().isOk()).andExpect(model().attributeExists("pet"))
.param("birthDate", "2015-02-12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "name"))
.andExpect(model().attributeHasFieldErrorCode("pet", "name", "duplicate"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdatePetForm")); .andExpect(view().name("pets/createOrUpdatePetForm"));
}
@Test
void testProcessCreationFormWithMissingPetType() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty")
.param("birthDate", "2015-02-12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "type"))
.andExpect(model().attributeHasFieldErrorCode("pet", "type", "required"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdatePetForm"));
}
@Test
void testProcessCreationFormWithInvalidBirthDate() throws Exception {
LocalDate currentDate = LocalDate.now();
String futureBirthDate = currentDate.plusMonths(1).toString();
mockMvc
.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty")
.param("birthDate", futureBirthDate))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "birthDate"))
.andExpect(model().attributeHasFieldErrorCode("pet", "birthDate", "typeMismatch.birthDate"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdatePetForm"));
}
@Test
void testInitUpdateForm() throws Exception {
mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID))
.andExpect(status().isOk())
.andExpect(model().attributeExists("pet"))
.andExpect(view().name("pets/createOrUpdatePetForm"));
}
} }
@Test @Test
void testProcessUpdateFormSuccess() throws Exception { void testProcessUpdateFormSuccess() throws Exception {
mockMvc mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty")
.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection())
.param("type", "hamster") .andExpect(view().name("redirect:/owners/{ownerId}"));
.param("birthDate", "2015-02-12"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
} }
@Nested @Test
class ProcessUpdateFormHasErrors { void testProcessUpdateFormHasErrors() throws Exception {
mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty")
@Test .param("birthDate", "2015/02/12")).andExpect(model().attributeHasNoErrors("owner"))
void testProcessUpdateFormWithInvalidBirthDate() throws Exception { .andExpect(model().attributeHasErrors("pet")).andExpect(status().isOk())
mockMvc
.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", " ")
.param("birthDate", "2015/02/12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "birthDate"))
.andExpect(model().attributeHasFieldErrorCode("pet", "birthDate", "typeMismatch"))
.andExpect(view().name("pets/createOrUpdatePetForm")); .andExpect(view().name("pets/createOrUpdatePetForm"));
}
@Test
void testProcessUpdateFormWithBlankName() throws Exception {
mockMvc
.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", " ")
.param("birthDate", "2015-02-12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(model().attributeHasFieldErrors("pet", "name"))
.andExpect(model().attributeHasFieldErrorCode("pet", "name", "required"))
.andExpect(view().name("pets/createOrUpdatePetForm"));
}
} }
} }

View file

@ -28,7 +28,6 @@ import java.util.Locale;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ -39,7 +38,6 @@ import org.mockito.junit.jupiter.MockitoExtension;
* @author Colin But * @author Colin But
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@DisabledInNativeImage
class PetTypeFormatterTests { class PetTypeFormatterTests {
@Mock @Mock
@ -68,7 +66,7 @@ class PetTypeFormatterTests {
} }
@Test @Test
void shouldThrowParseException() { void shouldThrowParseException() throws ParseException {
given(this.pets.findPetTypes()).willReturn(makePetTypes()); given(this.pets.findPetTypes()).willReturn(makePetTypes());
Assertions.assertThrows(ParseException.class, () -> { Assertions.assertThrows(ParseException.class, () -> {
petTypeFormatter.parse("Fish", Locale.ENGLISH); petTypeFormatter.parse("Fish", Locale.ENGLISH);

View file

@ -1,117 +0,0 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.validation.Errors;
import org.springframework.validation.MapBindingResult;
import java.time.LocalDate;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test class for {@link PetValidator}
*
* @author Wick Dynex
*/
@ExtendWith(MockitoExtension.class)
@DisabledInNativeImage
public class PetValidatorTests {
private PetValidator petValidator;
private Pet pet;
private PetType petType;
private Errors errors;
private static final String petName = "Buddy";
private static final String petTypeName = "Dog";
private static final LocalDate petBirthDate = LocalDate.of(1990, 1, 1);
@BeforeEach
void setUp() {
petValidator = new PetValidator();
pet = new Pet();
petType = new PetType();
errors = new MapBindingResult(new HashMap<>(), "pet");
}
@Test
void testValidate() {
petType.setName(petTypeName);
pet.setName(petName);
pet.setType(petType);
pet.setBirthDate(petBirthDate);
petValidator.validate(pet, errors);
assertFalse(errors.hasErrors());
}
@Nested
class ValidateHasErrors {
@Test
void testValidateWithInvalidPetName() {
petType.setName(petTypeName);
pet.setName("");
pet.setType(petType);
pet.setBirthDate(petBirthDate);
petValidator.validate(pet, errors);
assertTrue(errors.hasFieldErrors("name"));
}
@Test
void testValidateWithInvalidPetType() {
pet.setName(petName);
pet.setType(null);
pet.setBirthDate(petBirthDate);
petValidator.validate(pet, errors);
assertTrue(errors.hasFieldErrors("type"));
}
@Test
void testValidateWithInvalidBirthDate() {
petType.setName(petTypeName);
pet.setName(petName);
pet.setType(petType);
pet.setBirthDate(null);
petValidator.validate(pet, errors);
assertTrue(errors.hasFieldErrors("birthDate"));
}
}
}

View file

@ -25,24 +25,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.aot.DisabledInAotMode; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
/** /**
* Test class for {@link VisitController} * Test class for {@link VisitController}
* *
* @author Colin But * @author Colin But
* @author Wick Dynex
*/ */
@WebMvcTest(VisitController.class) @WebMvcTest(VisitController.class)
@DisabledInNativeImage
@DisabledInAotMode
class VisitControllerTests { class VisitControllerTests {
private static final int TEST_OWNER_ID = 1; private static final int TEST_OWNER_ID = 1;
@ -52,7 +45,7 @@ class VisitControllerTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@MockitoBean @MockBean
private OwnerRepository owners; private OwnerRepository owners;
@BeforeEach @BeforeEach
@ -61,34 +54,28 @@ class VisitControllerTests {
Pet pet = new Pet(); Pet pet = new Pet();
owner.addPet(pet); owner.addPet(pet);
pet.setId(TEST_PET_ID); pet.setId(TEST_PET_ID);
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(owner)); given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
} }
@Test @Test
void testInitNewVisitForm() throws Exception { void testInitNewVisitForm() throws Exception {
mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)) mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID))
.andExpect(status().isOk()) .andExpect(status().isOk()).andExpect(view().name("pets/createOrUpdateVisitForm"));
.andExpect(view().name("pets/createOrUpdateVisitForm"));
} }
@Test @Test
void testProcessNewVisitFormSuccess() throws Exception { void testProcessNewVisitFormSuccess() throws Exception {
mockMvc mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID)
.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID) .param("name", "George").param("description", "Visit Description"))
.param("name", "George") .andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/owners/{ownerId}"));
.param("description", "Visit Description"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
} }
@Test @Test
void testProcessNewVisitFormHasErrors() throws Exception { void testProcessNewVisitFormHasErrors() throws Exception {
mockMvc mockMvc.perform(
.perform(post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID).param("name", post("/owners/{ownerId}/pets/{petId}/visits/new", TEST_OWNER_ID, TEST_PET_ID).param("name", "George"))
"George")) .andExpect(model().attributeHasErrors("visit")).andExpect(status().isOk())
.andExpect(model().attributeHasErrors("visit")) .andExpect(view().name("pets/createOrUpdateVisitForm"));
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdateVisitForm"));
} }
} }

View file

@ -20,13 +20,13 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Collection; import java.util.Collection;
import java.util.Optional;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.samples.petclinic.owner.Owner; import org.springframework.samples.petclinic.owner.Owner;
@ -36,6 +36,7 @@ import org.springframework.samples.petclinic.owner.PetType;
import org.springframework.samples.petclinic.owner.Visit; import org.springframework.samples.petclinic.owner.Visit;
import org.springframework.samples.petclinic.vet.Vet; import org.springframework.samples.petclinic.vet.Vet;
import org.springframework.samples.petclinic.vet.VetRepository; import org.springframework.samples.petclinic.vet.VetRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
/** /**
@ -66,7 +67,7 @@ import org.springframework.transaction.annotation.Transactional;
* @author Michael Isvy * @author Michael Isvy
* @author Dave Syer * @author Dave Syer
*/ */
@DataJpaTest @DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class))
// Ensure that if the mysql profile is active we connect to the real database: // Ensure that if the mysql profile is active we connect to the real database:
@AutoConfigureTestDatabase(replace = Replace.NONE) @AutoConfigureTestDatabase(replace = Replace.NONE)
// @TestPropertySource("/application-postgres.properties") // @TestPropertySource("/application-postgres.properties")
@ -82,18 +83,16 @@ class ClinicServiceTests {
@Test @Test
void shouldFindOwnersByLastName() { void shouldFindOwnersByLastName() {
Page<Owner> owners = this.owners.findByLastNameStartingWith("Davis", pageable); Page<Owner> owners = this.owners.findByLastName("Davis", pageable);
assertThat(owners).hasSize(2); assertThat(owners).hasSize(2);
owners = this.owners.findByLastNameStartingWith("Daviss", pageable); owners = this.owners.findByLastName("Daviss", pageable);
assertThat(owners).isEmpty(); assertThat(owners).isEmpty();
} }
@Test @Test
void shouldFindSingleOwnerWithPet() { void shouldFindSingleOwnerWithPet() {
Optional<Owner> optionalOwner = this.owners.findById(1); Owner owner = this.owners.findById(1);
assertThat(optionalOwner).isPresent();
Owner owner = optionalOwner.get();
assertThat(owner.getLastName()).startsWith("Franklin"); assertThat(owner.getLastName()).startsWith("Franklin");
assertThat(owner.getPets()).hasSize(1); assertThat(owner.getPets()).hasSize(1);
assertThat(owner.getPets().get(0).getType()).isNotNull(); assertThat(owner.getPets().get(0).getType()).isNotNull();
@ -103,7 +102,7 @@ class ClinicServiceTests {
@Test @Test
@Transactional @Transactional
void shouldInsertOwner() { void shouldInsertOwner() {
Page<Owner> owners = this.owners.findByLastNameStartingWith("Schultz", pageable); Page<Owner> owners = this.owners.findByLastName("Schultz", pageable);
int found = (int) owners.getTotalElements(); int found = (int) owners.getTotalElements();
Owner owner = new Owner(); Owner owner = new Owner();
@ -113,18 +112,16 @@ class ClinicServiceTests {
owner.setCity("Wollongong"); owner.setCity("Wollongong");
owner.setTelephone("4444444444"); owner.setTelephone("4444444444");
this.owners.save(owner); this.owners.save(owner);
assertThat(owner.getId()).isNotZero(); assertThat(owner.getId().longValue()).isNotEqualTo(0);
owners = this.owners.findByLastNameStartingWith("Schultz", pageable); owners = this.owners.findByLastName("Schultz", pageable);
assertThat(owners.getTotalElements()).isEqualTo(found + 1); assertThat(owners.getTotalElements()).isEqualTo(found + 1);
} }
@Test @Test
@Transactional @Transactional
void shouldUpdateOwner() { void shouldUpdateOwner() {
Optional<Owner> optionalOwner = this.owners.findById(1); Owner owner = this.owners.findById(1);
assertThat(optionalOwner).isPresent();
Owner owner = optionalOwner.get();
String oldLastName = owner.getLastName(); String oldLastName = owner.getLastName();
String newLastName = oldLastName + "X"; String newLastName = oldLastName + "X";
@ -132,9 +129,7 @@ class ClinicServiceTests {
this.owners.save(owner); this.owners.save(owner);
// retrieving new name from database // retrieving new name from database
optionalOwner = this.owners.findById(1); owner = this.owners.findById(1);
assertThat(optionalOwner).isPresent();
owner = optionalOwner.get();
assertThat(owner.getLastName()).isEqualTo(newLastName); assertThat(owner.getLastName()).isEqualTo(newLastName);
} }
@ -151,10 +146,7 @@ class ClinicServiceTests {
@Test @Test
@Transactional @Transactional
void shouldInsertPetIntoDatabaseAndGenerateId() { void shouldInsertPetIntoDatabaseAndGenerateId() {
Optional<Owner> optionalOwner = this.owners.findById(6); Owner owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent();
Owner owner6 = optionalOwner.get();
int found = owner6.getPets().size(); int found = owner6.getPets().size();
Pet pet = new Pet(); Pet pet = new Pet();
@ -163,14 +155,12 @@ class ClinicServiceTests {
pet.setType(EntityUtils.getById(types, PetType.class, 2)); pet.setType(EntityUtils.getById(types, PetType.class, 2));
pet.setBirthDate(LocalDate.now()); pet.setBirthDate(LocalDate.now());
owner6.addPet(pet); owner6.addPet(pet);
assertThat(owner6.getPets()).hasSize(found + 1); assertThat(owner6.getPets().size()).isEqualTo(found + 1);
this.owners.save(owner6); this.owners.save(owner6);
optionalOwner = this.owners.findById(6); owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent(); assertThat(owner6.getPets().size()).isEqualTo(found + 1);
owner6 = optionalOwner.get();
assertThat(owner6.getPets()).hasSize(found + 1);
// checks that id has been generated // checks that id has been generated
pet = owner6.getPet("bowser"); pet = owner6.getPet("bowser");
assertThat(pet.getId()).isNotNull(); assertThat(pet.getId()).isNotNull();
@ -178,11 +168,8 @@ class ClinicServiceTests {
@Test @Test
@Transactional @Transactional
void shouldUpdatePetName() { void shouldUpdatePetName() throws Exception {
Optional<Owner> optionalOwner = this.owners.findById(6); Owner owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent();
Owner owner6 = optionalOwner.get();
Pet pet7 = owner6.getPet(7); Pet pet7 = owner6.getPet(7);
String oldName = pet7.getName(); String oldName = pet7.getName();
@ -190,9 +177,7 @@ class ClinicServiceTests {
pet7.setName(newName); pet7.setName(newName);
this.owners.save(owner6); this.owners.save(owner6);
optionalOwner = this.owners.findById(6); owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent();
owner6 = optionalOwner.get();
pet7 = owner6.getPet(7); pet7 = owner6.getPet(7);
assertThat(pet7.getName()).isEqualTo(newName); assertThat(pet7.getName()).isEqualTo(newName);
} }
@ -211,10 +196,7 @@ class ClinicServiceTests {
@Test @Test
@Transactional @Transactional
void shouldAddNewVisitForPet() { void shouldAddNewVisitForPet() {
Optional<Owner> optionalOwner = this.owners.findById(6); Owner owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent();
Owner owner6 = optionalOwner.get();
Pet pet7 = owner6.getPet(7); Pet pet7 = owner6.getPet(7);
int found = pet7.getVisits().size(); int found = pet7.getVisits().size();
Visit visit = new Visit(); Visit visit = new Visit();
@ -223,25 +205,22 @@ class ClinicServiceTests {
owner6.addVisit(pet7.getId(), visit); owner6.addVisit(pet7.getId(), visit);
this.owners.save(owner6); this.owners.save(owner6);
owner6 = this.owners.findById(6);
assertThat(pet7.getVisits()) // assertThat(pet7.getVisits()) //
.hasSize(found + 1) // .hasSize(found + 1) //
.allMatch(value -> value.getId() != null); .allMatch(value -> value.getId() != null);
} }
@Test @Test
void shouldFindVisitsByPetId() { void shouldFindVisitsByPetId() throws Exception {
Optional<Owner> optionalOwner = this.owners.findById(6); Owner owner6 = this.owners.findById(6);
assertThat(optionalOwner).isPresent();
Owner owner6 = optionalOwner.get();
Pet pet7 = owner6.getPet(7); Pet pet7 = owner6.getPet(7);
Collection<Visit> visits = pet7.getVisits(); Collection<Visit> visits = pet7.getVisits();
assertThat(visits) // assertThat(visits) //
.hasSize(2) // .hasSize(2) //
.element(0) .element(0).extracting(Visit::getDate).isNotNull();
.extracting(Visit::getDate)
.isNotNull();
} }
} }

View file

@ -1,99 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.system;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
/**
* Integration Test for {@link CrashController}.
*
* @author Alex Lutz
*/
// NOT Waiting https://github.com/spring-projects/spring-boot/issues/5574
@SpringBootTest(webEnvironment = RANDOM_PORT,
properties = { "server.error.include-message=ALWAYS", "management.endpoints.enabled-by-default=false" })
class CrashControllerIntegrationTests {
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
static class TestConfiguration {
}
@Value(value = "${local.server.port}")
private int port;
@Autowired
private TestRestTemplate rest;
@Test
void testTriggerExceptionJson() {
ResponseEntity<Map<String, Object>> resp = rest.exchange(
RequestEntity.get("http://localhost:" + port + "/oups").build(),
new ParameterizedTypeReference<Map<String, Object>>() {
});
assertThat(resp).isNotNull();
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(resp.getBody()).containsKey("timestamp");
assertThat(resp.getBody()).containsKey("status");
assertThat(resp.getBody()).containsKey("error");
assertThat(resp.getBody()).containsEntry("message",
"Expected: controller used to showcase what happens when an exception is thrown");
assertThat(resp.getBody()).containsEntry("path", "/oups");
}
@Test
void testTriggerExceptionHtml() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(List.of(MediaType.TEXT_HTML));
ResponseEntity<String> resp = rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET,
new HttpEntity<>(headers), String.class);
assertThat(resp).isNotNull();
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(resp.getBody()).isNotNull();
// html:
assertThat(resp.getBody()).containsSubsequence("<body>", "<h2>", "Something happened...", "</h2>", "<p>",
"Expected:", "controller", "used", "to", "showcase", "what", "happens", "when", "an", "exception", "is",
"thrown", "</p>", "</body>");
// Not the whitelabel error page:
assertThat(resp.getBody()).doesNotContain("Whitelabel Error Page",
"This application has no explicit mapping for");
}
}

View file

@ -16,26 +16,33 @@
package org.springframework.samples.petclinic.system; package org.springframework.samples.petclinic.system;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** /**
* Test class for {@link CrashController} * Test class for {@link CrashController}
* *
* @author Colin But * @author Colin But
* @author Alex Lutz
*/ */
// Waiting https://github.com/spring-projects/spring-boot/issues/5574 ..good // Waiting https://github.com/spring-projects/spring-boot/issues/5574
// luck ((plain(st) UNIT test)! :) @Disabled
@WebMvcTest(controllers = CrashController.class)
class CrashControllerTests { class CrashControllerTests {
final CrashController testee = new CrashController(); @Autowired
private MockMvc mockMvc;
@Test @Test
void testTriggerException() { void testTriggerException() throws Exception {
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> testee.triggerException()) mockMvc.perform(get("/oups")).andExpect(view().name("exception"))
.withMessageContaining("Expected: controller used to showcase what happens when an exception is thrown"); .andExpect(model().attributeExists("exception")).andExpect(forwardedUrl("exception"))
.andExpect(status().isOk());
} }
} }

View file

@ -19,14 +19,12 @@ package org.springframework.samples.petclinic.vet;
import org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.context.aot.DisabledInAotMode;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -41,14 +39,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/ */
@WebMvcTest(VetController.class) @WebMvcTest(VetController.class)
@DisabledInNativeImage
@DisabledInAotMode
class VetControllerTests { class VetControllerTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@MockitoBean @MockBean
private VetRepository vets; private VetRepository vets;
private Vet james() { private Vet james() {
@ -75,26 +71,24 @@ class VetControllerTests {
void setup() { void setup() {
given(this.vets.findAll()).willReturn(Lists.newArrayList(james(), helen())); given(this.vets.findAll()).willReturn(Lists.newArrayList(james(), helen()));
given(this.vets.findAll(any(Pageable.class))) given(this.vets.findAll(any(Pageable.class)))
.willReturn(new PageImpl<Vet>(Lists.newArrayList(james(), helen()))); .willReturn(new PageImpl<Vet>(Lists.newArrayList(james(), helen())));
} }
@Test @Test
void testShowVetListHtml() throws Exception { void testShowVetListHtml() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/vets.html?page=1")) mockMvc.perform(MockMvcRequestBuilders.get("/vets.html?page=1")).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(model().attributeExists("listVets")).andExpect(view().name("vets/vetList"));
.andExpect(model().attributeExists("listVets"))
.andExpect(view().name("vets/vetList"));
} }
@Test @Test
void testShowResourcesVetList() throws Exception { void testShowResourcesVetList() throws Exception {
ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()); .andExpect(status().isOk());
actions.andExpect(content().contentType(MediaType.APPLICATION_JSON)) actions.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.vetList[0].id").value(1)); .andExpect(jsonPath("$.vetList[0].id").value(1));
} }
} }

View file

@ -31,7 +31,6 @@ class VetTests {
vet.setFirstName("Zaphod"); vet.setFirstName("Zaphod");
vet.setLastName("Beeblebrox"); vet.setLastName("Beeblebrox");
vet.setId(123); vet.setId(123);
@SuppressWarnings("deprecation")
Vet other = (Vet) SerializationUtils.deserialize(SerializationUtils.serialize(vet)); Vet other = (Vet) SerializationUtils.deserialize(SerializationUtils.serialize(vet));
assertThat(other.getFirstName()).isEqualTo(vet.getFirstName()); assertThat(other.getFirstName()).isEqualTo(vet.getFirstName());
assertThat(other.getLastName()).isEqualTo(vet.getLastName()); assertThat(other.getLastName()).isEqualTo(vet.getLastName());

View file

@ -1,13 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.5"> <jmeterTestPlan version="1.2" properties="2.8" jmeter="2.13 r1665067">
<hashTree> <hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true"> <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
<stringProp name="TestPlan.comments"></stringProp> <stringProp name="TestPlan.comments"></stringProp>
<boolProp name="TestPlan.functional_mode">false</boolProp> <boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp> <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
guiclass="ArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments"> <collectionProp name="Arguments.arguments">
<elementProp name="PETCLINIC_HOST" elementType="Argument"> <elementProp name="PETCLINIC_HOST" elementType="Argument">
<stringProp name="Argument.name">PETCLINIC_HOST</stringProp> <stringProp name="Argument.name">PETCLINIC_HOST</stringProp>
@ -29,12 +27,9 @@
<stringProp name="TestPlan.user_define_classpath"></stringProp> <stringProp name="TestPlan.user_define_classpath"></stringProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="User threads" <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="User threads" enabled="true">
enabled="true">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp> <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Contr<74>leur Boucle" enabled="true">
guiclass="LoopControlPanel" testclass="LoopController" testname="Contr<74>leur Boucle"
enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp> <boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">10</stringProp> <stringProp name="LoopController.loops">10</stringProp>
</elementProp> </elementProp>
@ -49,17 +44,13 @@
<stringProp name="TestPlan.comments">Original : 500 - 10 - 10</stringProp> <stringProp name="TestPlan.comments">Original : 500 - 10 - 10</stringProp>
</ThreadGroup> </ThreadGroup>
<hashTree> <hashTree>
<ConstantTimer guiclass="ConstantTimerGui" testclass="ConstantTimer" <ConstantTimer guiclass="ConstantTimerGui" testclass="ConstantTimer" testname="Fixed time counter" enabled="true">
testname="Fixed time counter" enabled="true">
<stringProp name="ConstantTimer.delay">300</stringProp> <stringProp name="ConstantTimer.delay">300</stringProp>
</ConstantTimer> </ConstantTimer>
<hashTree /> <hashTree/>
<ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" <ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" testname="Default HTTP parameters" enabled="true">
testname="Default HTTP parameters" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain">${PETCLINIC_HOST}</stringProp> <stringProp name="HTTPSampler.domain">${PETCLINIC_HOST}</stringProp>
<stringProp name="HTTPSampler.port">${PETCLINIC_PORT}</stringProp> <stringProp name="HTTPSampler.port">${PETCLINIC_PORT}</stringProp>
@ -70,39 +61,33 @@
<stringProp name="HTTPSampler.path"></stringProp> <stringProp name="HTTPSampler.path"></stringProp>
<stringProp name="HTTPSampler.concurrentPool">4</stringProp> <stringProp name="HTTPSampler.concurrentPool">4</stringProp>
</ConfigTestElement> </ConfigTestElement>
<hashTree /> <hashTree/>
<CookieManager guiclass="CookiePanel" testclass="CookieManager" <CookieManager guiclass="CookiePanel" testclass="CookieManager" testname="HTTP cookie manager" enabled="true">
testname="HTTP cookie manager" enabled="true"> <collectionProp name="CookieManager.cookies"/>
<collectionProp name="CookieManager.cookies" />
<boolProp name="CookieManager.clearEachIteration">true</boolProp> <boolProp name="CookieManager.clearEachIteration">true</boolProp>
</CookieManager> </CookieManager>
<hashTree /> <hashTree/>
<CounterConfig guiclass="CounterConfigGui" testclass="CounterConfig" testname="User Count" <CounterConfig guiclass="CounterConfigGui" testclass="CounterConfig" testname="User Count" enabled="true">
enabled="true">
<stringProp name="CounterConfig.start">1</stringProp> <stringProp name="CounterConfig.start">1</stringProp>
<stringProp name="CounterConfig.end">3</stringProp> <stringProp name="CounterConfig.end">10</stringProp>
<stringProp name="CounterConfig.incr">1</stringProp> <stringProp name="CounterConfig.incr">1</stringProp>
<stringProp name="CounterConfig.name">count</stringProp> <stringProp name="CounterConfig.name">count</stringProp>
<stringProp name="CounterConfig.format"></stringProp> <stringProp name="CounterConfig.format"></stringProp>
<boolProp name="CounterConfig.per_user">false</boolProp> <boolProp name="CounterConfig.per_user">false</boolProp>
</CounterConfig> </CounterConfig>
<hashTree /> <hashTree/>
<CounterConfig guiclass="CounterConfigGui" testclass="CounterConfig" testname="Pet Count" <CounterConfig guiclass="CounterConfigGui" testclass="CounterConfig" testname="Pet Count" enabled="true">
enabled="true">
<stringProp name="CounterConfig.start">1</stringProp> <stringProp name="CounterConfig.start">1</stringProp>
<stringProp name="CounterConfig.end">3</stringProp> <stringProp name="CounterConfig.end">13</stringProp>
<stringProp name="CounterConfig.incr">1</stringProp> <stringProp name="CounterConfig.incr">1</stringProp>
<stringProp name="CounterConfig.name">petCount</stringProp> <stringProp name="CounterConfig.name">petCount</stringProp>
<stringProp name="CounterConfig.format"></stringProp> <stringProp name="CounterConfig.format"></stringProp>
<boolProp name="CounterConfig.per_user">false</boolProp> <boolProp name="CounterConfig.per_user">false</boolProp>
</CounterConfig> </CounterConfig>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Home page" enabled="true">
testname="Home page" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -119,13 +104,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="CSS" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="CSS" enabled="true">
enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -142,13 +124,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="JS" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="JS" enabled="true">
enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -156,7 +135,7 @@
<stringProp name="HTTPSampler.response_timeout"></stringProp> <stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp> <stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp> <stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/webjars/bootstrap/dist/js/bootstrap.bundle.min.js</stringProp> <stringProp name="HTTPSampler.path">${CONTEXT_WEB}/webjars/jquery/jquery.min.js</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp> <stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp> <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp> <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
@ -165,13 +144,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Vets" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Vets" enabled="true">
enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -188,13 +164,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Find owner" enabled="true">
testname="Find owner" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -211,13 +184,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Find owner with lastname=&quot;&quot;" enabled="true">
testname="Find owner with lastname=&quot;&quot;" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -234,13 +204,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Owner" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Owner" enabled="true">
enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -257,13 +224,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Edit Owner" enabled="true">
testname="Edit Owner" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -280,47 +244,15 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POST Edit Owner" enabled="true">
testname="POST Edit Owner" enabled="true"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments"> <collectionProp name="Arguments.arguments">
<elementProp name="firstName" elementType="HTTPArgument"> <elementProp name="" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp> <boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">Test</stringProp> <stringProp name="Argument.value">firstName=Test&amp;lastName=${count}&amp;address=1234+Test+St.&amp;city=TestCity&amp;telephone=612345678</stringProp>
<stringProp name="Argument.metadata">=</stringProp> <stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">firstName</stringProp>
</elementProp>
<elementProp name="lastName" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">${count}</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">lastName</stringProp>
</elementProp>
<elementProp name="address" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">1234+Test+St.</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">address</stringProp>
</elementProp>
<elementProp name="city" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">TestCity</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">city</stringProp>
</elementProp>
<elementProp name="telephone" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">612345678</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">telephone</stringProp>
</elementProp> </elementProp>
</collectionProp> </collectionProp>
</elementProp> </elementProp>
@ -339,13 +271,10 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="New visit" enabled="true">
testname="New Pet" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <collectionProp name="Arguments.arguments"/>
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
@ -353,107 +282,31 @@
<stringProp name="HTTPSampler.response_timeout"></stringProp> <stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp> <stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp> <stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/new</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy>
<hashTree />
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy"
testname="POST new pet" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments"
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments">
<elementProp name="name" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">Test+Fluffy+${petCount}</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">name</stringProp>
</elementProp>
<elementProp name="birthDate" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">2020-12-20</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">birthDate</stringProp>
</elementProp>
<elementProp name="type" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">cat</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">type</stringProp>
</elementProp>
</collectionProp>
</elementProp>
<stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/new</stringProp>
<stringProp name="HTTPSampler.method">POST</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy>
<hashTree />
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy"
testname="New visit" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments"
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp>
<stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/${petCount}/visits/new</stringProp> <stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/${petCount}/visits/new</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp> <stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp> <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp> <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp> <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POST new visit" enabled="true">
testname="POST new visit" enabled="true"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies"
enabled="true">
<collectionProp name="Arguments.arguments"> <collectionProp name="Arguments.arguments">
<elementProp name="date" elementType="HTTPArgument"> <elementProp name="" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp> <boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">2013-02-22</stringProp> <stringProp name="Argument.value">date=2013%2F02%2F22&amp;description=visit</stringProp>
<stringProp name="Argument.metadata">=</stringProp> <stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">date</stringProp>
</elementProp>
<elementProp name="description" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">visit</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
<boolProp name="HTTPArgument.use_equals">true</boolProp>
<stringProp name="Argument.name">description</stringProp>
</elementProp> </elementProp>
</collectionProp> </collectionProp>
</elementProp> </elementProp>
<stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp> <stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp> <stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp> <stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/${petCount}/visits/new</stringProp> <stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}/pets/${petCount}/visits/new</stringProp>
@ -465,9 +318,28 @@
<boolProp name="HTTPSampler.monitor">false</boolProp> <boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp> <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy> </HTTPSamplerProxy>
<hashTree /> <hashTree/>
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Owner" enabled="true">
testname="Results" enabled="false"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="Variables pr<70>-d<>finies" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.domain"></stringProp>
<stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">${CONTEXT_WEB}/owners/${count}</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<boolProp name="HTTPSampler.monitor">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
</HTTPSamplerProxy>
<hashTree/>
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="Results" enabled="false">
<boolProp name="ResultCollector.error_logging">false</boolProp> <boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp> <objProp>
<name>saveConfig</name> <name>saveConfig</name>
@ -499,9 +371,8 @@
</objProp> </objProp>
<stringProp name="filename"></stringProp> <stringProp name="filename"></stringProp>
</ResultCollector> </ResultCollector>
<hashTree /> <hashTree/>
<ResultCollector guiclass="StatVisualizer" testclass="ResultCollector" <ResultCollector guiclass="StatVisualizer" testclass="ResultCollector" testname="Aggregated report" enabled="true">
testname="Aggregated report" enabled="true">
<boolProp name="ResultCollector.error_logging">false</boolProp> <boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp> <objProp>
<name>saveConfig</name> <name>saveConfig</name>
@ -533,7 +404,7 @@
</objProp> </objProp>
<stringProp name="filename"></stringProp> <stringProp name="filename"></stringProp>
</ResultCollector> </ResultCollector>
<hashTree /> <hashTree/>
</hashTree> </hashTree>
</hashTree> </hashTree>
</hashTree> </hashTree>