# Org / Springframework / Samples / Petclinic / System

## Overview

The `org.springframework.samples.petclinic.system` package contains the application’s cross-cutting web support: the landing-page controller, the crash-demo controller, internationalization wiring, and cache setup. In Petclinic, this module appears to act as the “system” layer for user-facing behavior that is not tied to a domain entity such as owners, pets, or visits.

A new engineer can think of this package as the place where the application’s basic web experience is assembled: requests for `/` are routed to the welcome view, `/oups` deliberately throws an exception to exercise error handling, locale changes are enabled through a request parameter, and JCache is configured for application caches.

## Key Classes and Interfaces

### `WelcomeController`

Source: [src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java](src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java:22)

`WelcomeController` is a minimal Spring MVC controller whose only responsibility is to map the root path (`/`) to the `welcome` view. It is intentionally small, which makes it a clear entry point for the application’s home page.

- **Role in the module:** Provides the landing page route.
- **Key method:** [`welcome()`](src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java:25)
  - **What it does:** Handles `GET /` and returns the logical view name `welcome`.
  - **Parameters:** None.
  - **Returns:** A `String` view name.
  - **Side effects:** None; it does not populate a model or call other services.

Because the method returns only a view name, the controller relies on the view layer to render the actual homepage content.

### `WebConfiguration`

Source: [src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:23)

`WebConfiguration` enables internationalization support for the web layer. It configures how the application remembers the active locale and how users can change language at request time.

- **Role in the module:** Centralizes locale-related MVC configuration.
- **Implements:** `WebMvcConfigurer`, which lets the class contribute interceptor configuration to Spring MVC.

Key methods:

- [`localeResolver()`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:32)
  - **What it does:** Creates a `SessionLocaleResolver` and sets English as the default locale.
  - **Parameters:** None.
  - **Returns:** A `LocaleResolver` bean.
  - **Side effects:** Stores locale state in the user session so the chosen language persists across requests.

- [`localeChangeInterceptor()`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:44)
  - **What it does:** Creates a `LocaleChangeInterceptor` that looks for the `lang` request parameter.
  - **Parameters:** None.
  - **Returns:** A `LocaleChangeInterceptor` bean.
  - **Side effects:** Allows requests like `?lang=de` or `?lang=es` to switch the active locale.

- [`addInterceptors(InterceptorRegistry registry)`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:55)
  - **What it does:** Registers the locale change interceptor with Spring MVC.
  - **Parameters:** `InterceptorRegistry registry`, the MVC registry to update.
  - **Returns:** Nothing.
  - **Side effects:** Makes locale switching active for all intercepted web requests.

This configuration is the glue that connects locale-aware views and message bundles to the request lifecycle.

### `CacheConfiguration`

Source: [src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:31)

`CacheConfiguration` configures JCache integration for the application. It enables caching and creates the cache named `vets`, with statistics enabled so cache performance can be monitored.

- **Role in the module:** Supplies the cache manager customization used by the app.
- **Annotations of note:** `@EnableCaching` turns on Spring’s cache abstraction.

Key methods:

- [`petclinicCacheConfigurationCustomizer()`](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:35)
  - **What it does:** Returns a `JCacheManagerCustomizer` that creates the `vets` cache when the cache manager is initialized.
  - **Parameters:** None.
  - **Returns:** A `JCacheManagerCustomizer` bean.
  - **Side effects:** Registers the cache through the JCache manager at startup.

- [`cacheConfiguration()`](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:49)
  - **What it does:** Builds a simple `MutableConfiguration` and enables cache statistics.
  - **Parameters:** None.
  - **Returns:** A JCache `Configuration<Object, Object>`.
  - **Side effects:** Enables statistics collection, which is useful for observability and JMX access.

This class does not define eviction, sizing, or expiration policy. That suggests those concerns are expected to come from the selected JCache provider rather than this module.

### `CrashController`

Source: [src/main/java/org/springframework/samples/petclinic/system/CrashController.java](src/main/java/org/springframework/samples/petclinic/system/CrashController.java:28)

`CrashController` is a demonstration controller that deliberately fails when invoked. It exists to show how the application behaves when an exception is thrown and how the error view responds.

- **Role in the module:** Exercises error handling paths.
- **Design intent:** This appears to be a sample/diagnostic controller rather than a production endpoint.

Key method:

- [`triggerException()`](src/main/java/org/springframework/samples/petclinic/system/CrashController.java:31)
  - **What it does:** Handles `GET /oups` and immediately throws a `RuntimeException`.
  - **Parameters:** None.
  - **Returns:** Declared as `String`, but it never returns because it throws an exception first.
  - **Side effects:** Triggers Spring Boot’s error handling pipeline.

The exception message is intentionally descriptive: “Expected: controller used to showcase what happens when an exception is thrown”. That message is validated by the tests and also surfaces in the error response.

### `package-info.java`

Source: [src/main/java/org/springframework/samples/petclinic/system/package-info.java](src/main/java/org/springframework/samples/petclinic/system/package-info.java:17)

This file currently only declares the package. It does not contain package-level annotations or Javadoc, but it establishes the namespace for the controllers and configuration classes in this module.

### `CrashControllerTests`

Source: [src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java](src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java:31)

This unit test verifies the controller’s failure behavior without starting the full application context.

- **Key test:** [`triggerException()`](src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java:35)
  - **What it checks:** Calling `CrashController.triggerException()` throws a `RuntimeException` with the expected message.
  - **Why it matters:** Confirms the controller is intentionally failing and that the error text remains stable.

The test constructs the controller directly, which keeps the test focused and fast.

### `CrashControllerIntegrationTests`

Source: [src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java](src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java:50)

This integration test exercises the crash endpoint through HTTP and checks how Spring Boot renders the resulting error response in different formats.

- **Role in the module:** Verifies end-to-end error handling and response rendering.
- **Test setup:** Starts the application on a random port and disables actuator management endpoints via test properties.

Key tests:

- [`triggerExceptionJson()`](src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java:61)
  - **What it does:** Sends a request to `/oups` and expects a JSON error response.
  - **Asserts:** HTTP 500 status, and a body containing `timestamp`, `status`, `error`, `message`, and `path`.
  - **Important detail:** Confirms that the exception message is included in the response body.

- [`triggerExceptionHtml()`](src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java:77)
  - **What it does:** Sends the same request with `Accept: text/html` and expects an HTML error page.
  - **Asserts:** HTTP 500 status, a body containing the friendly error message, and no Whitelabel Error Page content.
  - **Important detail:** Confirms that the custom error page is used instead of the default fallback.

- [`TestConfiguration`](src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java:95)
  - **What it does:** Supplies a minimal `@SpringBootApplication` for the test context.
  - **Side effects:** Excludes `DataSourceAutoConfiguration`, `DataSourceTransactionManagerAutoConfiguration`, and `HibernateJpaAutoConfiguration` so the test can start without a database.

### `I18nPropertiesSyncTest`

Source: [src/test/java/org/springframework/samples/petclinic/system/I18nPropertiesSyncTest.java](src/test/java/org/springframework/samples/petclinic/system/I18nPropertiesSyncTest.java:25)

This test is a repository-wide safeguard for internationalization consistency. It is not specific only to the `system` package, but it supports the configuration here by ensuring translated resources stay aligned.

- **Role in the module:** Guards against missing translations and non-internationalized UI text.
- **Behavior:** Scans Java and HTML files under `src/main`, flags hard-coded HTML text literals, and checks that locale-specific property files contain the same keys as the base `messages.properties` file.

Key tests:

- [`checkNonInternationalizedStrings()`](src/test/java/org/springframework/samples/petclinic/system/I18nPropertiesSyncTest.java:39)
  - **What it does:** Walks source files and reports literal HTML text that is not backed by message expressions.
  - **Why it matters:** Encourages message-bundle usage instead of hard-coded user-facing strings.

- [`checkI18nPropertyFilesAreInSync()`](src/test/java/org/springframework/samples/petclinic/system/I18nPropertiesSyncTest.java:86)
  - **What it does:** Compares each locale properties file against the base messages file and reports missing keys.
  - **Why it matters:** Prevents partially translated bundles from slipping into the application.

## How It Works

### Request flow for the home page

1. A browser sends `GET /`.
2. Spring MVC dispatches the request to [`WelcomeController.welcome()`](src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java:25).
3. The controller returns the logical view name `welcome`.
4. The view resolver renders the corresponding template.

This flow is intentionally simple: the controller does not prepare data, which keeps the homepage route easy to reason about.

### Locale switching flow

1. A request arrives with a `lang` parameter, such as `?lang=de`.
2. [`WebConfiguration.localeChangeInterceptor()`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:44) provides the interceptor that watches for this parameter.
3. [`WebConfiguration.addInterceptors(...)`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:55) registers the interceptor with Spring MVC.
4. The [`SessionLocaleResolver`](src/main/java/org/springframework/samples/petclinic/system/WebConfiguration.java:32) stores the resolved locale in the session.
5. Subsequent requests reuse the same locale until changed again.

This design keeps language selection per user session rather than per request.

### Error-handling demo flow

1. A client requests `GET /oups`.
2. [`CrashController.triggerException()`](src/main/java/org/springframework/samples/petclinic/system/CrashController.java:31) throws a `RuntimeException` immediately.
3. Spring Boot’s error handling intercepts the failure.
4. If the client expects JSON, the response body contains the error fields validated by the integration test.
5. If the client expects HTML, the custom error view is rendered instead of the Whitelabel error page.

The tests document both branches, which makes this controller useful as a regression fixture for error-page behavior.

### Cache initialization flow

1. The application starts with caching enabled because of `@EnableCaching` on [`CacheConfiguration`](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:31).
2. Spring asks for the `JCacheManagerCustomizer` bean from [`petclinicCacheConfigurationCustomizer()`](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:35).
3. The customizer creates a cache named `vets`.
4. The cache uses [`cacheConfiguration()`](src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java:49), which enables statistics.

This is a narrow configuration: it creates the cache the application expects and leaves provider-specific tuning to the underlying JCache implementation.

## Dependencies and Integration

This package integrates with several Spring web and caching features:

- **Spring MVC** for controller mappings and interceptor registration.
- **Spring Web internationalization support** via `LocaleResolver` and `LocaleChangeInterceptor`.
- **Spring caching abstraction** via `@EnableCaching`.
- **JCache API** for cache creation and statistics.
- **Spring Boot error handling** as exercised by the crash controller tests.

The package does not appear to depend on domain-model packages directly. Its responsibility is infrastructural and cross-cutting rather than business-domain specific.

## Relationships at a Glance

```mermaid
flowchart TD
SystemPkg["org.springframework.samples.petclinic.system"] --> WelcomeController["WelcomeController"]
SystemPkg --> WebConfiguration["WebConfiguration"]
SystemPkg --> CacheConfiguration["CacheConfiguration"]
SystemPkg --> CrashController["CrashController"]
WebConfiguration --> LocaleResolver["SessionLocaleResolver bean"]
WebConfiguration --> LocaleChangeInterceptor["LocaleChangeInterceptor bean"]
CacheConfiguration --> JCacheManagerCustomizer["JCacheManagerCustomizer bean"]
CrashController --> ErrorHandling["Spring Boot error handling"]
WelcomeController --> WelcomeView["welcome view"]
```

## Notes for Developers

- `WelcomeController` and `CrashController` are intentionally tiny. If you add behavior, keep the methods focused on routing and delegate business logic elsewhere.
- `WebConfiguration` uses the `lang` request parameter as the locale switch. If you change that parameter name, update any UI links and tests that rely on it.
- `CacheConfiguration` currently creates only one cache, `vets`. If more caches are introduced, add them here so cache startup remains centralized.
- The crash endpoint exists to prove error handling, not to support a user workflow. Be careful not to treat it like a production API.
- `I18nPropertiesSyncTest` is a repository guardrail. If you add new user-facing strings or translation keys, expect this test to require matching updates in the message files.

## Typical Error Handling Sequence

```mermaid
sequenceDiagram
participant Browser as Browser
participant Crash as CrashController
participant Error as Spring Boot error handling
participant View as Error page
Browser ->> Crash - GET /oups
Crash ->> Error - throw RuntimeException
Error ->> View - render matching error response
Browser ->> Browser - display JSON or HTML error output
```

## Summary

The `system` package provides the application’s basic web infrastructure: homepage routing, locale selection, cache setup, and a controlled failure endpoint used to validate error behavior. It is small, but it plays an important role in defining how the app feels to users and how the platform behaves around requests, caching, and errors.
