Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,7 @@ out/
_site/
*.css
!petclinic.css

# macOS
.DS_Store
**/.DS_Store
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# syntax=docker/dockerfile:1
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn -q -DskipTests package

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app/app.jar"]
14 changes: 14 additions & 0 deletions docker-compose.app.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
app:
build: .
depends_on:
db:
condition: service_healthy
environment:
SPRING_PROFILES_ACTIVE: postgres
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/petclinic
SPRING_DATASOURCE_USERNAME: pet
SPRING_DATASOURCE_PASSWORD: pet
SPRING_SQL_INIT_MODE: "never"
ports:
- "8080:8080"
34 changes: 17 additions & 17 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
version: "3.9"

services:
mysql:
image: mysql:9.2
ports:
- "3306:3306"
db:
image: postgres:16-alpine
container_name: petclinic-db
environment:
- MYSQL_ROOT_PASSWORD=
- MYSQL_ALLOW_EMPTY_PASSWORD=true
- MYSQL_USER=petclinic
- MYSQL_PASSWORD=petclinic
- MYSQL_DATABASE=petclinic
volumes:
- "./conf.d:/etc/mysql/conf.d:ro"
postgres:
image: postgres:18.0
POSTGRES_USER: pet
POSTGRES_PASSWORD: pet
POSTGRES_DB: petclinic
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=petclinic
- POSTGRES_USER=petclinic
- POSTGRES_DB=petclinic
healthcheck:
test: ["CMD-SHELL", "pg_isready -U pet -d petclinic"]
interval: 5s
retries: 10
volumes:
- db_data:/var/lib/postgresql/data

volumes:
db_data:
26 changes: 26 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.4</version>
<scope>runtime</scope>
</dependency>

Expand Down Expand Up @@ -114,6 +115,13 @@
<artifactId>font-awesome</artifactId>
<version>${webjars-font-awesome.version}</version>
</dependency>
<!-- Testcontainers: PostgreSQL module -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.20.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -133,13 +141,31 @@
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.20.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- OpenAPI/Swagger UI -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>

<!-- Prometheus metrics registry -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<dependency>
<groupId>jakarta.xml.bind</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.springframework.samples.petclinic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;

@Configuration
public class SecurityConfig {

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// Security headers
.headers(h -> h
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'"))
.frameOptions(f -> f.sameOrigin())
.referrerPolicy(r -> r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)))
// Everything is public in this app
.authorizeHttpRequests(
a -> a.requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/actuator/**")
.permitAll()
.anyRequest()
.permitAll())
// Kill default auth mechanisms to avoid 401 challenges
.httpBasic(h -> h.disable())
.formLogin(f -> f.disable())
// Keep CSRF defaults (safe for GETs)
.csrf(Customizer.withDefaults());

return http.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

/**
* Repository class for <code>Owner</code> domain objects. All method names are compliant
Expand All @@ -39,26 +38,21 @@
public interface OwnerRepository extends JpaRepository<Owner, Integer> {

/**
* Retrieve {@link Owner}s from the data store by last name, returning all owners
* whose last name <i>starts</i> with the given name.
* @param lastName Value to search for
* @return a Collection of matching {@link Owner}s (or an empty Collection if none
* found)
* Retrieve {@link Owner}s whose last name starts with the given prefix. Example:
* "Hop" matches "Hopper".
*/
Page<Owner> findByLastNameStartingWith(String lastName, Pageable pageable);

/**
* 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
* @return an {@link Optional} containing the {@link Owner} if found, or an empty
* {@link Optional} if not found.
* @throws IllegalArgumentException if the id is null (assuming null is not a valid
* input for id)
* Retrieve {@link Owner}s whose last name matches exactly the given value. This is
* used by tests (e.g., OwnerRepositoryIT).
*/
List<Owner> findByLastName(String lastName);

/**
* Retrieve an {@link Owner} from the data store by id. Returns an empty Optional if
* not found.
* @throws IllegalArgumentException if the id is null
*/
Optional<Owner> findById(@Nonnull Integer id);

Expand Down
7 changes: 0 additions & 7 deletions src/main/resources/application-postgres.properties

This file was deleted.

27 changes: 27 additions & 0 deletions src/main/resources/application-postgres.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
spring:
datasource:
url: jdbc:postgresql://localhost:5432/petclinic
username: pet
password: pet
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
sql:
init:
mode: never

server:
port: 8080

management:
endpoints:
web:
exposure:
include: health,info,prometheus
endpoint:
health:
show-details: always
11 changes: 11 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
management:
endpoints:
web:
exposure:
include: health,info,prometheus

springdoc:
api-docs:
enabled: true
swagger-ui:
path: /swagger-ui.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package org.springframework.samples.petclinic.owner;

import java.util.List;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

/**
* Integration test that uses a real PostgreSQL instance via Testcontainers.
*/
@Testcontainers
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class OwnerRepositoryIT {

// PostgreSQL container used as the backing database for tests
@Container
static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("petclinic")
.withUsername("pet")
.withPassword("pet");

// Configure Spring DataSource properties to point to the container
@DynamicPropertySource
static void dbProps(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", postgres::getJdbcUrl);
r.add("spring.datasource.username", postgres::getUsername);
r.add("spring.datasource.password", postgres::getPassword);
r.add("spring.jpa.hibernate.ddl-auto", () -> "update"); // automatically create
// schema for tests
r.add("spring.sql.init.mode", () -> "never"); // skip default SQL initialization
}

@Autowired
OwnerRepository owners;

private Owner seeded;

// Insert a sample Owner before each test
@BeforeEach
void seed() {
Owner o = new Owner();
o.setFirstName("Grace");
o.setLastName("Hopper");
o.setAddress("123 Main St");
o.setCity("NYC");
o.setTelephone("1234567890");
seeded = owners.save(o);
}

// Remove all Owners after each test to ensure isolation
@AfterEach
void cleanup() {
owners.deleteAll();
}

// Verify that searching by last name returns the expected Owner with all fields
@Test
void findsOwnerByLastName_andChecksAllFields() {
List<Owner> result = owners.findByLastName("Hopper");

Assertions.assertThat(result).hasSize(1);

Owner found = result.get(0);
Assertions.assertThat(found.getId()).isNotNull();
Assertions.assertThat(found.getFirstName()).isEqualTo("Grace");
Assertions.assertThat(found.getLastName()).isEqualTo("Hopper");
Assertions.assertThat(found.getAddress()).isEqualTo("123 Main St");
Assertions.assertThat(found.getCity()).isEqualTo("NYC");
Assertions.assertThat(found.getTelephone()).isEqualTo("1234567890");
Assertions.assertThat(found.getPets()).isEmpty();
}

// Verify that searching for an unknown last name returns no results
@Test
void returnsEmptyListForUnknownLastName() {
List<Owner> result = owners.findByLastName("DoesNotExist");
Assertions.assertThat(result).isEmpty();
}

}
Loading