scarfbench-dataset
#1
by brmcg - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- .gitignoreAdded+94
- CONTRIBUTING.mdAdded+1098
- README.md+250-1
- benchmark/business_domain/cart/jakarta/.dockerignoreAdded+41
- benchmark/business_domain/cart/jakarta/.mvn/wrapper/MavenWrapperDownloader.javaAdded+117
- benchmark/business_domain/cart/jakarta/.mvn/wrapper/maven-wrapper.propertiesAdded+2
- benchmark/business_domain/cart/jakarta/DockerfileAdded+36
- benchmark/business_domain/cart/jakarta/cart-ejb/pom.xmlAdded+36
- benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/ejb/Cart.javaAdded+36
- benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/ejb/CartBean.javaAdded+82
- benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/util/BookException.javaAdded+22
- benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/util/IdVerifier.javaAdded+29
- benchmark/business_domain/cart/jakarta/cart-ejb/src/main/resources/META-INF/MANIFEST.MFAdded+2
- benchmark/business_domain/cart/jakarta/cart-web/pom.xmlAdded+82
- benchmark/business_domain/cart/jakarta/cart-web/src/main/java/jakarta/tutorial/cart/web/CartResource.javaAdded+173
- benchmark/business_domain/cart/jakarta/cart-web/src/main/java/jakarta/tutorial/cart/web/RestApplication.javaAdded+25
- benchmark/business_domain/cart/jakarta/cart-web/src/main/liberty/config/server.xmlAdded+46
- benchmark/business_domain/cart/jakarta/cart-web/src/main/webapp/WEB-INF/beans.xmlAdded+7
- benchmark/business_domain/cart/jakarta/mvnwAdded+310
- benchmark/business_domain/cart/jakarta/mvnw.cmdAdded+182
- benchmark/business_domain/cart/jakarta/pom.xmlAdded+112
- benchmark/business_domain/cart/jakarta/test.shAdded+15
- benchmark/business_domain/cart/quarkus/.dockerignoreAdded+41
- benchmark/business_domain/cart/quarkus/.mvn/wrapper/MavenWrapperDownloader.javaAdded+117
- benchmark/business_domain/cart/quarkus/.mvn/wrapper/maven-wrapper.propertiesAdded+2
- benchmark/business_domain/cart/quarkus/DockerfileAdded+36
- benchmark/business_domain/cart/quarkus/cart-ejb/pom.xmlAdded+45
- benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/service/Cart.javaAdded+20
- benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/service/CartBean.javaAdded+70
- benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/util/BookException.javaAdded+11
- benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/util/IdVerifier.javaAdded+17
- benchmark/business_domain/cart/quarkus/cart-web/pom.xmlAdded+77
- benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.jvmAdded+98
- benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.legacy-jarAdded+94
- benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.nativeAdded+29
- benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.native-microAdded+32
- benchmark/business_domain/cart/quarkus/cart-web/src/main/java/quarkus/tutorial/cart/CartResource.javaAdded+174
- benchmark/business_domain/cart/quarkus/cart-web/src/main/resources/application.propertiesAdded+1
- benchmark/business_domain/cart/quarkus/mvnwAdded+332
- benchmark/business_domain/cart/quarkus/mvnw.cmdAdded+206
- benchmark/business_domain/cart/quarkus/pom.xmlAdded+102
- benchmark/business_domain/cart/quarkus/test.shAdded+15
- benchmark/business_domain/cart/spring/.dockerignoreAdded+41
- benchmark/business_domain/cart/spring/.mvn/wrapper/maven-wrapper.propertiesAdded+3
- benchmark/business_domain/cart/spring/DockerfileAdded+36
- benchmark/business_domain/cart/spring/cart-ejb/pom.xmlAdded+29
- benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/service/Cart.javaAdded+21
- benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/service/CartServiceImpl.javaAdded+68
- benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/util/BookException.javaAdded+11
- benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/util/IdVerifier.javaAdded+17
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Build outputdist/site/site/*.pyc__pycache__/*.py[cod]*$py.class
# Virtual environmentvenv/env/ENV/.venv/
# IDE.vscode/.idea/*.swp*.swo*~
# OS.DS_StoreThumbs.db
# Logs*.log
# Java*.class*.jar*.war*.ear*.narhs_err_pid*replay_pid*
# Java IDE / tooling.classpath.project.settings/.factorypath
# Maven**/target/dependency-reduced-pom.xmlpom.xml.tagpom.xml.releaseBackuppom.xml.versionsBackuppom.xml.nextrelease.properties
# Gradle**/.gradle/**/build/gradle-app.setting
# Docker*.tar*.tar.gzdocker-compose.override.yml.env.env.*!.env.example
# HTML / static build artifacts**/.sass-cache/**/.cache/
# Python.pytest_cache/.mypy_cache/.ruff_cache/.coveragecoverage.xmlhtmlcov/**/*.egg-info/.tox/.nox/pip-wheel-metadata/**/__pypackages__/**/.ipynb_checkpoints/
# MkDocs.mkdocs_cache/
# VS Code.vscode/
# Binaries*.png*.jpg*.dat*.pdf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098# Contributing to SCARFBench
This guide explains how to contribute a new application to the SCARFBench benchmark suite.
## Table of Contents
- [Getting Started](#getting-started)- [Contribution Workflow](#contribution-workflow)- [Overview](#overview)- [Required Files](#required-files)- [1. Dockerfile](#1-dockerfile)- [2. Makefile](#2-Makefile)- [3. Smoke Test (smoke.py)](#3-smoke-test-smokepy)- [Standard Patterns](#standard-patterns)- [Checklist](#checklist)
## Getting Started
### Prerequisites
Before contributing, ensure you have:- **Git** installed- **Docker** installed and running- **make**Makefile build tool- Basic familiarity with the three frameworks (Jakarta EE, Quarkus, Spring Boot)
### Forking the Repository
1. **Fork** the repository on GitHub by clicking the "Fork" button at the top right of the repository page2. **Clone** your fork locally: ```bash git clone https://github.com/<your-username>/scarfbench.git cd scarfbench ```3. **Add upstream** remote to keep your fork synchronized: ```bash git remote add upstream https://github.com/original-repo/scarfbench.git ```4. **Create a branch** for your contribution: ```bash git checkout -b add-<application-name> ```
## Contribution Workflow
Follow these steps to contribute a new benchmark application:
### 1. Choose Application Category
Determine which category your application belongs to:- `business_domain/` - Core business logic patterns- `dependency_injection/` - DI and configuration patterns- `infrastructure/` - Infrastructure services (concurrency, messaging, etc.)- `integration/` - External system integration (batch, messaging, web services)- `persistence/` - Database and persistence patterns- `presentation/` - Web UI and REST API patterns- `security/` - Authentication and authorization patterns- `whole_applications/` - Complete, production-like applications
### 2. Create Directory Structure
Create your application directory under the appropriate category:```bashmkdir -p benchmark/<category>/<your-app-name>/{jakarta,quarkus,spring}```
### 3. Implement Framework Variants
For each framework (Jakarta, Quarkus, Spring):1. Implement the application using framework-specific patterns2. Create `Dockerfile` (see [Dockerfile section](#1-dockerfile))3. Create `Makefile` (see [Makefile section](#2-Makefile))4. Create smoke tests - either `smoke.py` or `smoke/` folder (see [Smoke Test section](#3-smoke-test-smokepy))
### 4. Verify All Implementations
For each framework, run the complete test sequence:```bashcd benchmark/<category>/<your-app-name>/<framework>just build # Build Docker imagejust up # Start containerjust test # Run smoke tests (should PASS)just logs # Verify application logsjust down # Clean up```
Repeat for all three frameworks: `jakarta`, `quarkus`, and `spring`.
### 5. Document Your Application
Create a `README.md` in your application directory:```bashbenchmark/<category>/<your-app-name>/README.md```
Include:- **Purpose**: What the application demonstrates- **Key Features**: Technologies and patterns showcased- **Framework Implementations**: Brief notes on each variant- **Testing**: What the smoke tests validate
### 6. Submit Pull Request
Once all implementations are working:
1. **Commit your changes**: ```bash git add benchmark/<category>/<your-app-name> git commit -m "Add <application-name> benchmark for <category>" ```
2. **Push to your fork**: ```bash git push origin add-<application-name> ```
3. **Create Pull Request** on GitHub: - Go to your fork on GitHub - Click "New Pull Request" - Fill out the PR template (automatically populated) - Ensure all checklist items are completed - Submit for review
4. **Respond to feedback**: Maintainers may request changes or improvements
### 7. Keep Your Fork Updated
Sync with upstream before starting new contributions:```bashgit fetch upstreamgit checkout maingit merge upstream/maingit push origin main```
## Overview
Each benchmark application in SCARFBench should support three frameworks:- **Jakarta EE** (using Open Liberty)- **Quarkus**- **Spring Boot**
In addition to the source application files, each framework implementation requires three standard files:1. `Dockerfile` - Container definition2. `Makefile` - Build and run automation3. `smoke.py` - Automated smoke tests
**Note on Technology Choices**: This guide demonstrates examples using **Python**, **uv**, and **Playwright** for smoke tests. However, these are not strict requirements. You are free to implement smoke tests in any language (Shell, JavaScript, Go, Java, etc.) as long as your Dockerfile and Makefile's `test` target work correctly. See [Alternative Smoke Test Implementations](#alternative-smoke-test-implementations) for examples in other languages.
This guide uses the following applications as reference standards:
1. [`benchmark/infrastructure/concurrency-jobs`](benchmark/infrastructure/concurrency-jobs) for basic REST/HTTP applications2. [`benchmark/infrastructure/ejb-async`](benchmark/infrastructure/ejb-async) for applications requiring browser automation and UI testing3. [`benchmark/whole_applications/daytrader`](benchmark/whole_applications/daytrader) for complex, multi-framework applications with extensive smoke tests
## Required Files
### 1. Dockerfile
The Dockerfile creates a containerized environment for building and running your application.
#### Standard Structure (Basic Pattern)
For applications with simple REST/HTTP API testing:
```dockerfileFROM maven:3.9-eclipse-temurin-21
USER rootRUN apt-get update && apt-get install -y python3 curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy all project filesCOPY pom.xml .COPY src srcCOPY smoke.py .
# Default command matches your local workflow# Framework-specific goal to be replaced accordingly# | Framework | Maven Goal |# |-----------------------|-------------------------------|# | Jakarta/OpenLiberty | liberty:run |# | Quarkus | quarkus:dev |# | Spring | spring-boot:run |CMD ["mvn", "clean", "package", "<framework-specific-goal>"]```
#### Playwright Pattern (For UI/Browser Testing)
For applications requiring browser automation and UI testing (reference: [`benchmark/infrastructure/ejb-async`](benchmark/infrastructure/ejb-async)):
```dockerfileFROM maven:3.9-eclipse-temurin-21
# Run everything as root (needed for Playwright installation)USER root
# Install Python and needed tools (add python3-venv for virtual environment support)RUN apt-get update && apt-get install -y python3 python3-venv python3-pip curl && rm -rf /var/lib/apt/lists/*
# Create and activate virtual environment for Python dependencies (PEP 668 safe)RUN python3 -m venv /opt/venvENV PATH="/opt/venv/bin:$PATH"
# Shared browsers path so Chromium is cached onceENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwrightRUN mkdir -p /ms-playwright && chmod 755 /ms-playwright
# Install Playwright and Chromium dependencies inside venvRUN pip install --no-cache-dir --upgrade pip setuptools wheel \ && pip install --no-cache-dir playwright==1.47.0 \ && playwright install --with-deps chromium
WORKDIR /app
# Copy Maven wrapper first (cache efficient)COPY .mvn .mvnCOPY mvnw .RUN chmod +x mvnw
# Copy root pom and module poms for dependency layer cachingCOPY pom.xml ./# If you have multiple modules, copy each module's pom separately:# COPY module1/pom.xml module1/pom.xml# COPY module2/pom.xml module2/pom.xmlRUN ./mvnw -q -DskipTests dependency:go-offline || true
# Copy full module sourcesCOPY src src# If you have multiple modules:# COPY module1 module1# COPY module2 module2
# Copy unified smoke test (includes Playwright logic)COPY smoke.py .RUN chmod +x smoke.py
# For Playwright tests, CMD can run smoke.py directly or the Maven goal# Framework-specific goal to be replaced accordingly# | Framework | Maven Goal |# |-----------------------|-------------------------------|# | Jakarta/OpenLiberty | liberty:run |# | Quarkus | quarkus:dev |# | Spring | spring-boot:run |CMD ["mvn", "clean", "package", "<framework-specific-goal>"]```
#### Important Notes
1. **Python3 and curl**: Always install these for smoke tests2. **User ID 1001**: Standard non-root user for security (basic pattern only)3. **Root User for Playwright**: Playwright installation requires root privileges; use root user when browser automation is needed4. **Virtual Environment**: Use Python venv (`/opt/venv`) for Playwright to comply with PEP 6685. **File Ownership**: Use `--chown=1001:1001` for all COPY commands in basic pattern; omit in Playwright pattern (root owns everything)6. **smoke.py**: Must be copied into the container7. **No Port Exposure**: Do NOT use `EXPOSE` directive - tests run internally via `docker exec`, not through exposed ports8. **Maven Wrapper**: Ensure `mvnw` is executable with `chmod +x`9. **Layer Caching**: For Playwright pattern, copy pom.xml files first to cache dependencies separately from source code10. **Browser Path**: Set `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright` to share browser binaries across builds
### 2. Makefile
The Makefile provides standard commands for building, running, testing, and managing your application.
#### Standard Structure
```just### <Application Name> (<Framework>) MakefileAPP_NAME := "<app-name>-<framework>"IMAGE_NAME := "<app-name>-<framework>:latest"SUCCESS_PATTERN := "<framework-specific-pattern>"
build: docker build -f Dockerfile -t {{IMAGE_NAME}} . @echo "[INFO] Built image: {{IMAGE_NAME}}"
rebuild: docker build --no-cache -f Dockerfile -t {{IMAGE_NAME}} . @echo "[INFO] Rebuilt image (no cache): {{IMAGE_NAME}}"
up: build ### The below section will look for exisiting containers and if so, remove them. @if docker ps --all --quiet --filter name=^/{{APP_NAME}}$ | grep -q .; then \ echo "[INFO] Removing existing container"; \ docker rm -f {{APP_NAME}} >/dev/null; \ fi ### Run the container in detached mode docker run -d --name {{APP_NAME}} {{IMAGE_NAME}} @echo "[INFO] Started {{APP_NAME}}, waiting for app to start..."
### Check for build failure @until docker logs {{APP_NAME}} 2>&1 | grep -q "BUILD FAILURE"; do \ if docker logs {{APP_NAME}} 2>&1 | grep -q "{{SUCCESS_PATTERN}}"; then \ break; \ fi; \ sleep 1; \ done @if docker logs {{APP_NAME}} 2>&1 | grep -q "BUILD FAILURE"; then \ echo "[ERROR] Build failed in container:"; \ docker logs {{APP_NAME}} 2>&1; \ exit 1; \ fi
### Wait for success pattern @until docker logs {{APP_NAME}} 2>&1 | grep -q "{{SUCCESS_PATTERN}}"; do sleep 1; done @echo "[INFO] App started and ready."
logs: docker logs -f {{APP_NAME}}
down: - docker rm -f {{APP_NAME}} @echo "[INFO] Container removed (if it existed)"
test: up @docker exec {{APP_NAME}} sh -c 'python3 /app/smoke.py'
local: ./mvnw clean package <framework-goal>```
#### Framework-Specific Startup Patterns
The `SUCCESS_PATTERN` variable should be set based on the framework:
| Framework | Success Pattern | Example ||-----------|-----------------|---------|| Jakarta | `CWWKF0011I` | `SUCCESS_PATTERN := "CWWKF0011I"` || Quarkus | `started in.*Listening on:` | `SUCCESS_PATTERN := "started in.*Listening on:"` || Spring Boot | `Tomcat started on port\|Started .* in .* seconds` | `SUCCESS_PATTERN := "Tomcat started on port"` |
**Note**: These patterns are used in extended grep (`grep -E`), so use regex syntax where needed.
#### Startup Wait Loop Explained
The `up` target uses two separate checks:
1. **Build Failure Check**: Polls logs looking for `BUILD FAILURE` (a standard Maven failure message) - While checking, also looks for the success pattern - If success pattern found first, breaks out of the failure check - If `BUILD FAILURE` found: displays full logs and exits with error
2. **Success Pattern Wait**: If no build failure, continues waiting for the success pattern - Loops until the framework-specific success pattern appears in logs - Pattern indicates the application is fully started and ready
#### Port Notes
Applications bind to internal ports (usually `9080` or `8080`) for communication within the container. Since tests run internally via `docker exec`, **no port mapping to the host is needed**. The Makefile does not expose ports, and containers run without `-p` flags.
#### Required Targets
All Makefiles must include these standard targets:
- `build`: Build the Docker image- `rebuild`: Rebuild without cache (for troubleshooting)- `up`: Start container, wait for readiness- `logs`: Stream container logs- `down`: Stop and remove container- `test`: Run smoke tests- `local`: Run locally without Docker
### 3. Smoke Test (smoke.py or custom smoke tests)
The smoke test validates your application's core functionality. While examples below use Python, **you are free to write smoke tests in any language** - the only requirements are:
1. **Dockerfile** must exist and be able to run the tests2. **Makefile** must have a `test` target that executes the tests3. Tests must exit with code `0` on success, non-zero on failure
This allows flexibility to use:- Python with pytest/Playwright (recommended for complex UI testing)- Shell scripts with curl (lightweight HTTP testing)- JavaScript with Node.js (if you prefer JavaScript)- Go, Java, or any other language- Combinations of multiple test frameworks
The key requirement is that `just test` must work inside the container.
#### Standard Structure
```python#!/usr/bin/env python3"""Smoke test for <Application Name> (<Framework>).
Checks: 1) Discover reachable base path 2) <Test 1 description> 3) <Test 2 description> ...
Exit codes: 0 success, non-zero on first failure encountered."""import osimport sysimport timefrom urllib.request import Request, urlopenfrom urllib.error import HTTPError, URLError
# ConfigurationVERBOSE = os.getenv("VERBOSE") == "1"
# Base URL candidates (try in order)CANDIDATES = [ os.getenv("<APP>_BASE_URL"), # Environment variable override "http://localhost:<internal-port>/<path>/", # Container internal]
def vprint(msg: str): """Print only if VERBOSE=1""" if VERBOSE: print(msg)
def http_request( method: str, url: str, data: bytes | None = None, headers: dict | None = None, timeout: int = 10,): """Make HTTP request, return (status, body) or None on network error""" req = Request(url, data=data, method=method, headers=headers or {}) try: with urlopen(req, timeout=timeout) as resp: status = resp.getcode() body = resp.read().decode("utf-8", "replace") except HTTPError as e: status = e.code body = e.read().decode("utf-8", "replace") except (URLError, Exception) as e: return None, f"NETWORK-ERROR: {e}" return (status, body), None
def discover_base() -> str: """Try each candidate URL, return first working one""" for cand in CANDIDATES: if not cand: continue # Try to validate candidate if validate_candidate(cand): print(f"[INFO] Base discovered: {cand}") return cand # Fallback for cand in CANDIDATES: if cand: print(f"[WARN] No base validated, using fallback {cand}") return cand print("[ERROR] No base URL candidates available", file=sys.stderr) sys.exit(2)
def validate_candidate(base: str) -> bool: """Implement validation logic for your app""" # Example: Try a health check endpoint pass
def main(): start = time.time() base = discover_base() # Run your test sequence here # Example: # test_endpoint_1(base) # test_endpoint_2(base) elapsed = time.time() - start print(f"[PASS] Smoke sequence complete in {elapsed:.2f}s") return 0
if __name__ == "__main__": sys.exit(main())```
#### Key Components
1. **Docstring**: Describe what the smoke test validates2. **URL Discovery**: Try multiple URL candidates (env var, localhost variations, container ports)3. **HTTP Helper**: Reusable function for making requests4. **Verbose Logging**: Support `VERBOSE=1` environment variable5. **Exit Codes**: Use specific exit codes for different failure types6. **Pass/Fail Messages**: Clear `[PASS]`/`[FAIL]` prefixes7. **Timing**: Report total test execution time
#### Playwright-Based Testing (Advanced)
For applications requiring browser automation and UI testing, use Playwright. Example structure:
```python#!/usr/bin/env python3"""Smoke test with Playwright for UI validation.
Checks: 1) Start application server 2) Launch browser and navigate to UI 3) Interact with UI elements 4) Validate UI behavior and responses
Exit codes: 0 success, non-zero on failure."""import osimport sysimport timeimport subprocessfrom playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout
VERBOSE = os.getenv("VERBOSE") == "1"BASE_URL = "http://localhost:9080"
def vprint(msg: str): if VERBOSE: print(msg)
def start_server(): """Start the application server""" vprint("[INFO] Starting application server...") # Example: Start Liberty server proc = subprocess.Popen( ["./mvnw", "clean", "package", "liberty:run"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) # Wait for server to be ready for line in proc.stdout: vprint(line.rstrip()) if "CWWKF0011I" in line: # Liberty started print("[INFO] Server started successfully") break return proc
def test_ui_with_playwright(base_url: str): """Test UI using Playwright browser automation""" print("[INFO] Launching browser...") with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page() try: # Navigate to application vprint(f"[INFO] Navigating to {base_url}") page.goto(base_url, wait_until="networkidle", timeout=30000) # Example: Check page title title = page.title() if "Expected Title" not in title: print(f"[FAIL] Unexpected page title: {title}", file=sys.stderr) return False print(f"[PASS] Page title: {title}") # Example: Fill form and submit page.fill("#inputField", "test value") page.click("#submitButton") # Wait for response page.wait_for_selector(".result", timeout=10000) result = page.text_content(".result") if "expected result" not in result.lower(): print(f"[FAIL] Unexpected result: {result}", file=sys.stderr) return False print(f"[PASS] Form submission successful: {result}") return True except PlaywrightTimeout as e: print(f"[FAIL] Timeout: {e}", file=sys.stderr) return False except Exception as e: print(f"[FAIL] Error: {e}", file=sys.stderr) return False finally: browser.close()
def main(): start = time.time() # Start server server_proc = start_server() try: # Run UI tests success = test_ui_with_playwright(BASE_URL) if not success: return 1 elapsed = time.time() - start print(f"[PASS] Smoke sequence complete in {elapsed:.2f}s") return 0 finally: # Clean up if server_proc: vprint("[INFO] Stopping server...") server_proc.terminate() server_proc.wait()
if __name__ == "__main__": sys.exit(main())```
#### Playwright Testing Notes
1. **Browser Setup**: Use `chromium.launch(headless=True)` for CI/CD compatibility2. **Timeouts**: Set appropriate timeouts for page loads and element waits3. **Wait Strategies**: Use `wait_until="networkidle"` for page loads, `wait_for_selector` for elements4. **Error Handling**: Always use try/finally to ensure browser cleanup5. **Server Management**: Start application server before tests, terminate after6. **Selectors**: Use stable selectors (IDs, data attributes) instead of classes7. **Screenshots**: Capture on failure for debugging: `page.screenshot(path="error.png")`8. **Virtual Display**: In Docker, browsers run headless automatically
#### Best Practices
1. **Test Real Functionality**: Don't just check if the server responds - validate actual behavior2. **Multiple Scenarios**: Test with and without authentication, different inputs, etc.3. **Meaningful Assertions**: Check status codes AND response content4. **Clear Error Messages**: Include URL, status, and response body in failures5. **Early Exit**: Exit on first failure with specific exit code6. **Timeout Handling**: Use reasonable timeouts (10s default)7. **Network Resilience**: Handle both HTTP errors and network failures
#### Example Test Pattern
```pythondef test_endpoint(base: str, description: str, path: str, method: str = "GET", expected_status: int = 200, expected_content: str = None, headers: dict = None): """Reusable test function""" url = f"{base.rstrip('/')}{path}" resp, err = http_request(method, url, headers=headers) if err: print(f"[FAIL] {description}: {err}", file=sys.stderr) sys.exit(1) status, body = resp body_stripped = body.strip() if status != expected_status: print(f"[FAIL] {description}: Expected {expected_status}, got {status}", file=sys.stderr) sys.exit(1) if expected_content and expected_content not in body_stripped: print(f"[FAIL] {description}: Expected content '{expected_content}' not found", file=sys.stderr) sys.exit(1) print(f"[PASS] {description}")```
#### Smoke Test Folder Structure (For Complex Applications)
For large, multi-framework applications (reference: [`benchmark/whole_applications/daytrader`](benchmark/whole_applications/daytrader)), organize smoke tests in a dedicated folder with multiple test files and a dependency manifest:
**Folder Structure:**```<application>/<framework>/smoke/├── smoke.py # Main entry point with pytest fixtures├── test_*.py # Individual test modules├── playwright-test-cases.md # Documentation of test scenarios├── pyproject.toml # Python dependencies (pytest, pytest-playwright, etc.)├── pytest.ini # Pytest configuration├── conftest.py # Pytest fixtures and configuration└── README.md # Test documentation```
**pyproject.toml** (using `uv` for modern dependency management - recommended):```toml[project]name = "smoke"version = "0.1.0"description = "Smoke tests for <Application>"requires-python = ">=3.11"dependencies = [ "playwright>=1.47.0", "pytest>=8.0.0,<9.0.0", "pytest-playwright>=0.7.0",]
[tool.pytest.ini_options]testpaths = ["."]python_files = ["test_*.py", "smoke.py"]
# Optional: specify script entry point[project.scripts]smoke = "smoke:main"```
**conftest.py** (pytest fixtures):```pythonimport osimport pytestfrom playwright.sync_api import sync_playwright
BASE_URL = os.getenv("BASE_URL", "http://localhost:9080/app")
@pytest.fixturedef page(): """Provide a Playwright page fixture for all tests""" with sync_playwright() as p: browser = p.chromium.launch(headless=True) context = browser.new_context() page = context.new_page() yield page browser.close()
@pytest.fixturedef base_url(): """Provide base URL to all tests""" return BASE_URL```
**smoke.py** (example with pytest markers):```pythonimport pytestfrom playwright.sync_api import Page, expect
BASE_URL = "http://localhost:9080/app"
@pytest.mark.smokedef test_home_page_loads(page: Page) -> None: """Test that home page loads successfully""" page.goto(BASE_URL, wait_until="domcontentloaded") expect(page).to_have_title("Application Title")
@pytest.mark.smokedef test_navigation_links(page: Page) -> None: """Test that main navigation links are present""" page.goto(BASE_URL, wait_until="domcontentloaded") links = page.get_by_role("link") assert links.count() > 0
@pytest.mark.smokedef test_login_form(page: Page) -> None: """Test login functionality""" page.goto(f"{BASE_URL}/login", wait_until="domcontentloaded") page.fill('input[name="username"]', "testuser") page.fill('input[name="password"]', "password") page.click('button[type="submit"]') # Assert successful login assert page.url != f"{BASE_URL}/login"```
**Dockerfile Integration** (using `uv` for fast, reproducible test environments - recommended):```dockerfileFROM maven:3.9-eclipse-temurin-21
USER rootRUN apt-get update && apt-get install -y python3 curl && rm -rf /var/lib/apt/lists/*
# Install uv for fast Python dependency managementRUN curl -sSL https://astral.sh/uv/install.sh | shENV PATH="$HOME/.cargo/bin:$PATH"
WORKDIR /app
# Copy application filesCOPY pom.xml .COPY src srcCOPY .mvn .mvnCOPY mvnw .RUN chmod +x mvnw
# Copy entire smoke test folder (includes pyproject.toml, uv.lock, test files)COPY smoke smoke
CMD ["./mvnw", "clean", "package", "<framework-specific-goal>"]```
**Makefile Integration** (using `uv` with Playwright - recommended for complex apps):```just### <Application Name> (<Framework>) MakefileAPP_NAME := "<app-name>-<framework>"IMAGE_NAME := "<app-name>-<framework>:latest"APP_PORT := "9080"
build: docker build -f Dockerfile -t {{IMAGE_NAME}} . @echo "[INFO] Built image: {{IMAGE_NAME}}"
rebuild: docker build --no-cache -f Dockerfile -t {{IMAGE_NAME}} . @echo "[INFO] Rebuilt image (no cache): {{IMAGE_NAME}}"
up: build - docker rm -f {{APP_NAME}} 2>/dev/null || true docker run -d --name {{APP_NAME}} {{IMAGE_NAME}} @echo "[INFO] Started {{APP_NAME}} (internal port {{APP_PORT}})..." @echo "[INFO] Waiting for application to start..." @until docker logs {{APP_NAME}} 2>&1 | grep -q "<startup-pattern>"; do sleep 1; done @echo "[INFO] Application started, port {{APP_PORT}} is ready."
logs: docker logs -f {{APP_NAME}}
down: - docker rm -f {{APP_NAME}} @echo "[INFO] Container {{APP_NAME}} removed (if it existed)."
# Run Playwright-based smoke tests inside the running container with uvsmoke: up @echo "[INFO] Running smoke tests inside container {{APP_NAME}}..." docker exec {{APP_NAME}} bash -lc "cd smoke && uv sync && uv run playwright install chromium && uv run pytest -v --tb=short"
test: smoke
local: ./mvnw clean package <framework-specific-goal>```
**Key Benefits of Folder Structure:**
1. **Scalability**: Organize tests into multiple files as test suite grows2. **Modularity**: Separate concerns (auth tests, API tests, UI tests, etc.)3. **pytest Features**: Use markers, fixtures, and parameterization4. **Dependencies**: Centralized management in `pyproject.toml` with `uv.lock` for reproducibility5. **Documentation**: Each test file and test case is self-documenting6. **CI/CD Friendly**: pytest integrates with most CI/CD systems7. **Fast Dependency Sync**: `uv sync` is significantly faster than `pip install`
**Running Tests Locally (with `uv` - recommended):**```bashcd smokeuv sync # Install dependencies from pyproject.tomluv run pytest -v # Run all testsuv run pytest -m smoke # Run only smoke testsuv run pytest test_login.py # Run specific test fileuv run pytest -v --tb=short # Run with short tracebackVERBOSE=1 uv run pytest -v # Run with verbose output```
**Running Tests Locally (with pip - legacy approach):**```bashcd smokepip install -e . # Install from pyproject.tomlpytest -v # Run all testspytest -m smoke # Run only smoke tests```
#### Alternative Smoke Test Implementations
While Python with pytest is recommended for complex applications, here are other valid approaches:
**Shell Script Example** (simple HTTP testing):```bash#!/bin/bash# smoke.sh - Lightweight smoke test using curl
set -eBASE_URL="http://localhost:9080/app"
echo "[INFO] Testing home page..."curl -sf "$BASE_URL/" > /dev/null || exit 1
echo "[INFO] Testing API endpoint..."curl -sf "$BASE_URL/api/status" | grep -q "ok" || exit 1
echo "[PASS] Smoke tests complete"exit 0```
**JavaScript/Node.js Example** (with Jest):```javascript// smoke.test.jsconst axios = require('axios');
const BASE_URL = 'http://localhost:9080/app';
describe('Smoke Tests', () => { test('home page loads', async () => { const response = await axios.get(BASE_URL); expect(response.status).toBe(200); expect(response.data).toContain('app'); });
test('API endpoint responds', async () => { const response = await axios.get(`${BASE_URL}/api/status`); expect(response.data.status).toBe('ok'); });});```
**Makefile Integration** (shell script example):```justsmoke: up @echo "[INFO] Running smoke tests..." docker exec {{APP_NAME}} bash -c "cd /app && bash smoke.sh"
test: smoke```
**Key Point**: The implementation language doesn't matter, as long as:- The Dockerfile includes necessary runtime and dependencies- The `test` target in Makefile successfully runs the tests within the container- Tests exit with appropriate exit codes (0 = success)
## Standard Patterns
### Directory Structure
For **simple applications** (single smoke.py):```benchmark/<category>/<application-name>/├── jakarta/│ ├── Dockerfile│ ├── Makefile│ ├── smoke.py│ ├── pom.xml│ ├── mvnw│ ├── mvnw.cmd│ ├── .mvn/│ └── src/├── quarkus/│ ├── Dockerfile│ ├── Makefile│ ├── smoke.py│ ├── pom.xml│ ├── mvnw│ ├── mvnw.cmd│ ├── .mvn/│ └── src/└── spring/ ├── Dockerfile ├── Makefile ├── smoke.py ├── pom.xml ├── mvnw ├── mvnw.cmd ├── .mvn/ └── src/```
For **complex applications** (smoke folder with pytest):```benchmark/<category>/<application-name>/├── jakarta/│ ├── Dockerfile│ ├── Makefile│ ├── pom.xml│ ├── mvnw│ ├── mvnw.cmd│ ├── .mvn/│ ├── src/│ └── smoke/ # Folder instead of single file│ ├── smoke.py│ ├── test_home.py│ ├── test_auth.py│ ├── test_api.py│ ├── conftest.py│ ├── pytest.ini│ ├── pyproject.toml│ ├── playwright-test-cases.md│ └── README.md├── quarkus/│ ├── ... (same structure)│ └── smoke/│ └── ... (same structure)└── spring/ ├── ... (same structure) └── smoke/ └── ... (same structure)```
### Naming Conventions
1. **Container Names**: `<app>-<framework>` (e.g., `jobs-jakarta`, `jobs-quarkus`)2. **Image Names**: `<app>-<framework>:latest`3. **Variables**: Use uppercase with underscores (e.g., `APP_NAME`, `IMAGE_NAME`)4. **Paths**: Use consistent endpoint paths across frameworks
### Common Variables
These should appear in every Makefile:
```justAPP_NAME := "<app>-<framework>"IMAGE_NAME := "<app>-<framework>:latest"```
## Checklist
Before submitting your contribution, verify:
### Dockerfile- [ ] Uses appropriate JDK base image for framework- [ ] Installs `python3` and `curl`- [ ] **Basic pattern**: Creates non-root user with UID 1001- [ ] **Playwright pattern**: Runs as root and installs Python venv, pip, and Playwright- [ ] **Playwright pattern**: Sets up `PLAYWRIGHT_BROWSERS_PATH` and installs Chromium- [ ] Copies all necessary files with correct ownership (use `--chown=1001:1001` for basic pattern)- [ ] Makes `mvnw` executable- [ ] Does NOT include `EXPOSE` directive (tests run internally)- [ ] Uses correct Maven goal in CMD- [ ] **Playwright pattern**: Implements layer caching for pom.xml files
### Makefile- [ ] All variables defined at top (APP_NAME, IMAGE_NAME)- [ ] `build` target works- [ ] `rebuild` target works (no cache)- [ ] `up` target waits for correct startup pattern- [ ] `logs` target streams container logs- [ ] `down` target cleans up container- [ ] `test` target runs smoke tests successfully- [ ] `local` target runs app without Docker
### Smoke Test (smoke.py)- [ ] Has descriptive docstring- [ ] Includes shebang `#!/usr/bin/env python3`- [ ] Has URL discovery with multiple candidates- [ ] Supports `VERBOSE=1` environment variable- [ ] Tests real application functionality (not just health checks)- [ ] Uses clear `[PASS]`/`[FAIL]` messages- [ ] Exits with code 0 on success, non-zero on failure- [ ] Reports execution time- [ ] Handles network errors gracefully- [ ] Works both inside container and from host- [ ] **Playwright tests**: Properly manages browser lifecycle (launch/close)- [ ] **Playwright tests**: Uses appropriate timeouts and wait strategies- [ ] **Playwright tests**: Handles server startup and shutdown
### Testing- [ ] `just build` succeeds for all frameworks- [ ] `just up` starts container and waits for ready state- [ ] `just test` passes all smoke tests- [ ] `just logs` shows application logs- [ ] `just down` cleans up successfully- [ ] `just local` runs application locally- [ ] All three frameworks (jakarta, quarkus, spring) work identically- [ ] **Playwright tests**: Browser tests pass in headless mode- [ ] **Playwright tests**: Tests work both inside container and from host
### Documentation- [ ] Add README.md explaining the application's purpose- [ ] Document any special configuration or requirements- [ ] Document if Playwright is used for UI testing- [ ] Update main benchmark documentation if needed
## Tips and Troubleshooting
### Debugging
**Test startup pattern**: `docker logs <container> 2>&1 | grep -q "<pattern>"`
**Run smoke test manually**: `docker exec <container> python3 /app/smoke.py`
**Verbose output**: `VERBOSE=1 python3 smoke.py`
**Playwright debugging**: Set `headless=False` and use `page.pause()`
### Common Issues
**Container won't start**: Check logs with `docker logs <container>`
**Smoke test fails**: Run with `VERBOSE=1` to see detailed request/response
**Startup timeout**: Increase sleep or check startup pattern regex
**Permission denied**: Verify file ownership matches user UID 1001 (basic pattern only)
**Playwright browser won't launch**: Ensure you're running as root in Dockerfile or install system dependencies
**Playwright timeout**: Increase timeout values or check if page is actually loading
**Python package conflicts**: Use virtual environment with `python3 -m venv` (required for Playwright)
**Chromium not found**: Verify `playwright install chromium` ran successfully and `PLAYWRIGHT_BROWSERS_PATH` is set
## Quick Start
```bash# 1. Create structuremkdir -p benchmark/<category>/<app>/{jakarta,quarkus,spring}
# 2. Implement first frameworkcd benchmark/<category>/<app>/jakarta# ... create Dockerfile, Makefile, smoke.py
# 3. Testjust build && just up && just test
# 4. Adapt to other frameworks# 5. Submit PR```
## Reference Implementations
- **Basic pattern**: [`benchmark/infrastructure/concurrency-jobs`](benchmark/infrastructure/concurrency-jobs)- **Playwright pattern**: [`benchmark/infrastructure/ejb-async`](benchmark/infrastructure/ejb-async)- **Complex multi-test**: [`benchmark/whole_applications/daytrader`](benchmark/whole_applications/daytrader)123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252<picture><source media="(prefers-color-scheme: dark)" srcset="https://github.com/scarfbench/site/blob/main/public/assets/images/scarf-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://github.com/scarfbench/site/blob/main/public/assets/images/scarf-light.png"><img alt="Logo"></picture><div align="center"><a href="https://scarfbench.github.io/site"><img src="https://img.shields.io/badge/site-scarfbench.info-blue?style=for-the-badge" alt="Documentation"></a><a href="https://scarfbench.github.io/site/leaderboard/"><img src="https://img.shields.io/badge/leaderboard-view%20results-orange?style=for-the-badge" alt="Leaderboard"></a></div>**Scarf** (short for **S**elf-**C**ontained **A**pplication **R**efactoring) benchmark is a suite of Java applications across frameworks: Jakarta EE, Quarkus, and Spring for evaluating agentic transformation between the frameworks. This suite enables systematic assessment of AI agents' ability to migrate enterprise Java applications while preserving functionality, idiomatic patterns, and architectural integrity across different runtime environments.The benchmark includes comprehensive examples ranging from focused layer-specific demonstrations to complete production-grade applications, each with verified implementations across all supported frameworks.> **Note:** All applications in this benchmark have been meticulously converted and verified by experienced developers. Each implementation has undergone rigorous testing to ensure functional correctness, adherence to framework-specific idioms, and preservation of architectural integrity across Jakarta EE, Quarkus, and Spring frameworks.---## Table of Contents- [Quickstart Guide](#quickstart-guide)- [Benchmark Applications](#benchmark-applications)- [Focused Examples](#focused-examples)- [Whole Applications](#whole-applications)- [Roadmap](#roadmap)- [Contact](#contact)---## Quickstart GuideThis benchmark suite comes with most things needed to run the benchmark applications. Everything is already set up!### What's IncludedEach application comes with:- **Dockerfile** - Pre-configured container with all dependencies installed- **Makefile** - Simple commands to build and run everything- **smoke.py or smoke/** - Automated tests to verify the application worksYou don't need to install Maven, Java, or any dependencies. Docker handles it all!### PrerequisitesYou only need:- Docker installed on your machine- make command runner (you can install it via Cargo or your package manager)### Running an Application#### Step 1: Pick an ApplicationBrowse the directory structure and choose any application. For example:```business_domain/counter/spring/dependency_injection/encoder/jakarta/presentation/mood/quarkus/```#### Step 2: Navigate to the Application```bashcd business_domain/counter/spring```#### Step 3: Run It!```bashmake up```That's it! The `make up` command will:1. Build your application2. Build the Docker container3. Start everything up#### Step 4: Check the Logs```bashmake logs```#### Step 5: Stop When Done```bashmake down```### Common CommandsEvery application supports these commands (via the `Makefile`):| Command | What it does ||--------------|------------------------------------|| `make help` | Shows all available commands || `make up` | Builds and starts the application || `make logs` | Shows application logs || `make test` | Runs everything and the smoke tests|| `make clean` | Removes build artifacts |### Running Smoke TestsMost applications include automated tests. To run, just use `make test`:```bashmake test```### Framework VariationsEach application type comes in three flavors:- **jakarta/** - Jakarta EE (enterprise Java)- **quarkus/** - Quarkus (cloud-native Java)- **spring/** - Spring Boot (popular Java framework)Pick whichever framework you want to test!### Troubleshooting**Port already in use?**```bashmake rebuild```**Want to rebuild from scratch?**```bashmake cleanmake rebuildmake up```**Need to see what's happening?**```bashmake logs```---## Benchmark ApplicationsThis benchmark contains self-contained applications demonstrating core Java EE functionalities and their framework-specific implementations. Each example has been manually converted and verified across all target frameworks, with smoke tests included to verify application behavior after transformation.The benchmark includes two types of examples:### Focused ExamplesApplication examples organized per layer, where each example demonstrates a specific technology within that layer (e.g., persistence, presentation, integration).#### Business Domain LayerCore business logic implementations using Enterprise JavaBeans (EJBs). Demonstrates stateful, stateless, and singleton session beans for shopping carts, currency conversion, hit counters, web services, and standalone EJB usage.**Examples:**- **cart** - Stateful session bean with shopping cart lifecycle management and `@Remove` methods- **converter** - Stateless session bean demonstrating currency conversion business logic- **counter** - Singleton session bean with shared state for tracking web page hits- **helloservice** - JAX-WS web service implemented as a stateless session bean- **standalone** - Stateless session bean for standalone EJB container usage#### Dependency Injection LayerCDI and dependency injection patterns including custom qualifiers, interceptors, decorators, producer methods, event observers, and alternative implementations for conditional bean selection.#### Infrastructure LayerEnterprise features including managed executors for concurrency, asynchronous EJB methods, interceptors for cross-cutting concerns, and timer services for scheduled task execution.#### Integration LayerIntegration technologies featuring Jakarta Batch processing, JMS messaging patterns, message-driven beans, JAX-WS web services, and Java Connector Architecture for enterprise system integration.#### Persistence LayerData persistence patterns using JPA entities with CRUD operations, complex entity relationships, composite keys, inheritance strategies, and JPQL queries for database interactions.#### Presentation LayerWeb tier implementations including servlets, JAX-RS REST APIs, WebSocket endpoints, server-sent events, file uploads, filters, listeners, and real-time communication patterns.#### Security LayerAuthentication and authorization patterns featuring Jakarta Security identity stores, form-based and basic authentication, EJB security, role-based access control, and password hashing.---### Whole ApplicationsComplete, functioning applications that demonstrate the coordination and interaction between multiple layers.#### CargoTrackerDomain-Driven Design cargo shipping tracker with Jakarta Faces, CDI, Enterprise Beans, JPA, REST, Batch, and JMS. Showcases aggregates, repositories, and domain events following Eric Evans' DDD patterns.Demonstrates Jakarta Faces, CDI, Enterprise Beans, JPA, REST, Batch, JSON Binding, Bean Validation, and JMS. Showcases end-to-end application architecture with multiple interfaces (web UI, REST API, file scanning) and complex domain modeling including aggregates, repositories, and domain events. Implements the cargo tracking example from Eric Evans' DDD book.#### Coffee ShopEvent-driven microservices with Orders, Barista, and Kitchen services via Kafka. Demonstrates MicroProfile stack, reactive messaging, distributed transactions, and eventual consistency.Microservices architecture with Orders, Barista, and Kitchen services communicating via Apache Kafka. Demonstrates MicroProfile (Config, Health, OpenAPI, Metrics), JPA with PostgreSQL, JAX-RS REST APIs, reactive messaging patterns, and distributed transaction coordination. Shows event-driven architecture with asynchronous inter-service communication and eventual consistency.#### DayTraderHigh-performance stock trading benchmark with stateless session beans, JPA optimistic locking, transaction management, and connection pooling. Used for measuring server performance.Online stock trading benchmark application demonstrating real-world Java EE workload patterns. Implements user authentication, portfolio management, stock quote lookup, and buy/sell transactions. Showcases performance-oriented design with stateless session beans, JPA entities with optimistic locking, transaction management, connection pooling, and web service interfaces.#### PetClinicVeterinary clinic management with Jakarta Faces (PrimeFaces), complex JPA relationships, CDI, and Bean Validation. Complete workflows for owners, pets, visits, and veterinarians.Full-featured veterinary clinic management system using Jakarta Faces (PrimeFaces) for the UI layer. Demonstrates CRUD operations with JPA entities showing one-to-many, many-to-one, and many-to-many relationships (owners-pets, pets-visits, vets-specialties). Includes CDI beans, Bean Validation, JSF navigation, complex forms, and master-detail views.#### RealWorldMedium.com clone with MicroProfile JWT, JAX-RS REST API, article management, comments, favorites, tags, and user following. Includes Testcontainers integration tests.Medium.com clone (Conduit) implementing the RealWorld specification with full CRUD operations, JWT authentication, article management, comments, favorites, tags, and user following. Demonstrates MicroProfile JWT, JAX-RS REST API design, JPA with PostgreSQL, password hashing (BCrypt), slug generation, pagination, filtering, and comprehensive exception handling. Includes integration tests with Testcontainers and MicroShed testing framework.---## ContactFor any questions, feedback, or suggestions, or to submit your own agent results for the leaderboard, please contact the authors:| Name | Email || -------------- | ---------------------------------------- || Rahul Krishna | [i.m.ralk@gmail.com](mailto:imralk+oss@gmail.com) || Bridget McGinn | [bridget.mcginn@ibm.com](bridget.mcginn@ibm.com) || Raju Pavuluri | [pavuluri@us.ibm.com](mailto:pavuluri@us.ibm.com) |---## CitationIf you use this benchmark in your research, please cite our paper:```bibtex[Placeholder: BibTeX citation will be added when paper is published]```---## LicenseApache-2.0
1234567891011121314151617181920212223242526272829303132333435363738394041# VCS.git/
# Maven.mvn/**/.mvn/mvnwmvnw.cmd**/mvnw**/mvnw.cmdtarget/**/target/pom.xml.tagpom.xml.releaseBackuppom.xml.versionsBackuppom.xml.nextrelease.propertiesdependency-reduced-pom.xmlbuildNumber.properties
# IDE / Editor.vscode/**/.vscode/.zed/**/.zed/.idea/**/.idea/*.iml*.ipr*.iws
# OS.DS_Store**/.DS_StoreThumbs.dbehthumbs.db
# Logs / temp*.log*.tmp*.temp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117/* * 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 * * http://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(); }
}12distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zipwrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar123456789101112131415161718192021222324252627282930313233343536FROM maven:3.9.12-ibm-semeru-21-noble
USER root# install uvRUN apt-get update && apt-get install -y --no-install-recommends curl python3-venv python3-full \ && curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"
# Shared browsers path so Chromium is cached onceENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwrightRUN mkdir -p /ms-playwright && chmod 755 /ms-playwright
# create venv and installRUN uv venv /opt/venv \ && uv pip install --python /opt/venv/bin/python playwright==1.47.0 pytest
ENV PATH="/opt/venv/bin:$PATH"RUN playwright install --with-deps chromium
WORKDIR /app
# Cache Maven dependencies separately from source (multi-module)COPY pom.xml .COPY cart-ejb/pom.xml cart-ejb/COPY cart-web/pom.xml cart-web/RUN mvn dependency:go-offline -q
# Build applicationCOPY . .RUN mvn package -DskipTests -q
COPY test.sh .RUN chmod +x test.sh
CMD ["mvn", "liberty:run"]123456789101112131415161718192021222324252627282930313233343536<?xml version="1.0" encoding="UTF-8"?><!--
Copyright (c), Eclipse Foundation, Inc. and its licensors.
All rights reserved.
This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0, which is available at https://www.eclipse.org/org/documents/edl-v10.php
SPDX-License-Identifier: BSD-3-Clause
--><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>jakarta.examples.tutorial.ejb.cart</groupId> <artifactId>cart</artifactId> <version>10-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cart-ejb</artifactId> <version>10-SNAPSHOT</version> <packaging>jar</packaging>
<name>cart-ejb</name>
<properties> <jakarta.ejb.version>3.2</jakarta.ejb.version> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
</project>123456789101112131415161718192021222324252627282930313233343536/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.ejb;
import java.util.List;
import jakarta.ejb.Remote;import jakarta.tutorial.cart.util.BookException;
@Remotepublic interface Cart { public void initialize(String person) throws BookException;
public void initialize( String person, String id) throws BookException;
public void addBook(String title);
public void removeBook(String title) throws BookException;
public List<String> getContents();
public void remove();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.ejb;
import java.io.Serializable;import java.util.ArrayList;import java.util.List;
import jakarta.ejb.Stateful;import jakarta.tutorial.cart.util.BookException;import jakarta.tutorial.cart.util.IdVerifier;
@Statefulpublic class CartBean implements Cart, Serializable {
String customerId; String customerName; List<String> contents = new ArrayList<>();
@Override public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; }
customerId = "0"; contents = new ArrayList<>(); }
@Override public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; }
IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); }
contents = new ArrayList<>(); }
@Override public void addBook(String title) { contents.add(title); }
@Override public void removeBook(String title) throws BookException { boolean result = contents.remove(title);
if (result == false) { throw new BookException("\"" + title + "\" not in cart."); } }
@Override public List<String> getContents() { return contents; }
@Override public void remove() { contents = new ArrayList<>(); }}12345678910111213141516171819202122/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.util;
public class BookException extends Exception { private static final long serialVersionUID = 6274585742564840905L; public BookException() { }
public BookException(String msg) { super(msg); }}1234567891011121314151617181920212223242526272829/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.util;
public class IdVerifier { public IdVerifier() { }
public boolean validate(String id) { boolean result = true;
for (int i = 0; i < id.length(); i++) { if (Character.isDigit(id.charAt(i)) == false) { result = false; } }
return result; }}12Manifest-Version: 1.0
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182<?xml version="1.0" encoding="UTF-8"?><!--
Copyright (c), Eclipse Foundation, Inc. and its licensors.
All rights reserved.
This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0, which is available at https://www.eclipse.org/org/documents/edl-v10.php
SPDX-License-Identifier: BSD-3-Clause
--><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>jakarta.examples.tutorial.ejb.cart</groupId> <artifactId>cart</artifactId> <version>10-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cart-web</artifactId> <packaging>war</packaging>
<properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
<name>cart-web</name>
<dependencies> <dependency> <groupId>${project.groupId}</groupId> <artifactId>cart-ejb</artifactId> <version>${project.version}</version> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> <packagingIncludes>**/*.class,**/*.xml,**/*.properties,WEB-INF/lib/*.jar</packagingIncludes> </configuration> </plugin> <plugin> <groupId>io.openliberty.tools</groupId> <artifactId>liberty-maven-plugin</artifactId> <configuration> <assemblyArtifact> <groupId>io.openliberty</groupId> <artifactId>openliberty-kernel</artifactId> <version>${liberty.runtime.version}</version> <type>zip</type> </assemblyArtifact> <serverName>defaultServer</serverName> <stripVersion>true</stripVersion> <installAppPackages>project</installAppPackages> <looseApplication>true</looseApplication> <appsDirectory>apps</appsDirectory> </configuration> <executions> <execution> <id>package-server</id> <phase>package</phase> <goals> <goal>create</goal> <goal>install-feature</goal> <goal>deploy</goal> </goals> </execution> </executions> </plugin> </plugins> </build></project>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.web;
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;
import jakarta.ejb.EJB;import jakarta.enterprise.context.ApplicationScoped;import jakarta.tutorial.cart.ejb.Cart;import jakarta.tutorial.cart.util.BookException;import jakarta.ws.rs.Consumes;import jakarta.ws.rs.DELETE;import jakarta.ws.rs.GET;import jakarta.ws.rs.POST;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;
/** * REST resource for cart operations. * Provides HTTP endpoints to interact with the shopping cart EJB. */@Path("/cart")@ApplicationScoped@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public class CartResource {
@EJB private Cart cart;
/** * Initialize a new cart session. * POST /api/cart/initialize * Body: {"customerName": "John Doe", "customerId": "123"} */ @POST @Path("/initialize") public Response initializeCart(CustomerRequest request) { try { if (request.customerId != null && !request.customerId.isEmpty()) { cart.initialize(request.customerName, request.customerId); } else { cart.initialize(request.customerName); } Map<String, String> response = new HashMap<>(); response.put("message", "Cart initialized successfully"); response.put("customerName", request.customerName); return Response.ok(response).build(); } catch (BookException e) { return Response.status(Response.Status.BAD_REQUEST) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Add a book to the cart. * POST /api/cart/books/{title} */ @POST @Path("/books/{title}") public Response addBook(@PathParam("title") String title) { try { cart.addBook(title); Map<String, Object> response = new HashMap<>(); response.put("message", "Book added successfully"); response.put("title", title); response.put("cartSize", cart.getContents().size()); return Response.ok(response).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Remove a book from the cart. * DELETE /api/cart/books/{title} */ @DELETE @Path("/books/{title}") public Response removeBook(@PathParam("title") String title) { try { cart.removeBook(title); Map<String, Object> response = new HashMap<>(); response.put("message", "Book removed successfully"); response.put("title", title); response.put("cartSize", cart.getContents().size()); return Response.ok(response).build(); } catch (BookException e) { return Response.status(Response.Status.NOT_FOUND) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Get all books in the cart. * GET /api/cart/books */ @GET @Path("/books") public Response getBooks() { try { List<String> contents = cart.getContents(); Map<String, Object> response = new HashMap<>(); response.put("books", contents); response.put("count", contents.size()); return Response.ok(response).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Clear the cart and end the session. * DELETE /api/cart */ @DELETE public Response clearCart() { try { cart.remove(); return Response.ok(Map.of("message", "Cart cleared successfully")).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Health check endpoint. * GET /api/cart/health */ @GET @Path("/health") public Response health() { return Response.ok(Map.of("status", "UP", "service", "cart-api")).build(); }
// Request/Response DTOs public static class CustomerRequest { public String customerName; public String customerId; }}12345678910111213141516171819202122232425/* * Copyright (c), Eclipse Foundation, Inc. and its licensors. * * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v1.0, which is available at * https://www.eclipse.org/org/documents/edl-v10.php * * SPDX-License-Identifier: BSD-3-Clause */package jakarta.tutorial.cart.web;
import jakarta.ws.rs.ApplicationPath;import jakarta.ws.rs.core.Application;
/** * JAX-RS Application configuration class. * Maps the REST API to /api/* */@ApplicationPath("/api")public class RestApplication extends Application { // No additional configuration needed // JAX-RS will auto-discover resource classes}12345678910111213141516171819202122232425262728293031323334353637383940414243444546<?xml version="1.0" encoding="UTF-8"?><server description="Cart Application Server">
<!-- Enable features --> <featureManager> <feature>jakartaee-9.1</feature> <feature>localConnector-1.0</feature> </featureManager>
<!-- HTTP endpoint --> <httpEndpoint id="defaultHttpEndpoint" httpPort="9080" httpsPort="9443" host="*" />
<!-- Automatically expand WAR files --> <applicationManager autoExpand="true"/>
<!-- Application configuration --> <webApplication id="cart-web" location="cart-web.war" name="cart-web" contextRoot="/cart"> <application-bnd> <security-role name="**"> <special-subject type="ALL_AUTHENTICATED_USERS" /> </security-role> </application-bnd> </webApplication>
<!-- Basic user registry for development --> <basicRegistry id="basic" realm="BasicRealm"> <user name="admin" password="admin" /> </basicRegistry>
<!-- Administrator role --> <administrator-role> <user>admin</user> </administrator-role>
<!-- Logging configuration --> <logging consoleLogLevel="INFO" consoleFormat="simple" consoleSource="message,trace,accessLog,ffdc,audit" />
</server>1234567<?xml version="1.0" encoding="UTF-8"?><beans xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd" version="3.0" bean-discovery-mode="all"></beans>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310#!/bin/sh# ----------------------------------------------------------------------------# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# 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## http://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.# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------# Maven Start Up Batch script## Required ENV vars:# ------------------# JAVA_HOME - location of a JDK home dir## Optional ENV vars# -----------------# M2_HOME - location of maven2's installed home dir# MAVEN_OPTS - parameters passed to the Java VM when running Maven# e.g. to debug Maven itself, use# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000# MAVEN_SKIP_RC - flag to disable loading of mavenrc files# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi
if [ -f "$HOME/.mavenrc" ] ; then . "$HOME/.mavenrc" fi
fi
# OS specific support. $var _must_ be set to either true or false.cygwin=false;darwin=false;mingw=falsecase "`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 ;;esac
if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then JAVA_HOME=`java-config --jre-home` fifi
if [ -z "$M2_HOME" ] ; then ## resolve links - $0 may be a link to maven's home PRG="$0"
# need this for relative symlinks while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG="`dirname "$PRG"`/$link" fi done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir" # echo Using m2 at $M2_HOMEfi
# For Cygwin, ensure paths are in UNIX format before anything is touchedif $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 touchedif $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 fifi
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 else JAVACMD="`which java`" fifi
if [ ! -x "$JAVACMD" ] ; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1fi
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 directoryfind_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 fileconcat_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" fielse if [ "$MVNW_VERBOSE" = true ]; then echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." fi 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
if command -v wget > /dev/null; then 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 fifi########################################################################################### End of extension##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}if [ "$MVNW_VERBOSE" = true ]; then echo $MAVEN_PROJECTBASEDIRfiMAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running javaif $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 "$@"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182@REM ----------------------------------------------------------------------------@REM Licensed to the Apache Software Foundation (ASF) under one@REM or more contributor license agreements. See the NOTICE file@REM distributed with this work for additional information@REM regarding copyright ownership. The ASF licenses this file@REM to you under the Apache License, Version 2.0 (the@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@REM http://www.apache.org/licenses/LICENSE-2.0@REM@REM Unless required by applicable law or agreed to in writing,@REM software distributed under the License is distributed on an@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@REM KIND, either express or implied. See the License for the@REM specific language governing permissions and limitations@REM under the License.@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------@REM Maven Start Up Batch script@REM@REM Required ENV vars:@REM JAVA_HOME - location of a JDK home dir@REM@REM Optional ENV vars@REM M2_HOME - location of maven2's installed home dir@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands@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 Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'@echo off@REM set title of command windowtitle %0@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOMEif "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this oneif not "%MAVEN_SKIP_RC%" == "" goto skipRcPre@REM check for pre script, once with legacy .bat ending and once with .cmd endingif 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. >&2echo Please set the JAVA_HOME variable in your environment to match the >&2echo location of your Java installation. >&2echo.goto error
:OkJHomeif exist "%JAVA_HOME%\bin\java.exe" goto init
echo.echo Error: JAVA_HOME is set to an invalid directory. >&2echo JAVA_HOME = "%JAVA_HOME%" >&2echo Please set the JAVA_HOME variable in your environment to match the >&2echo location of your Java installation. >&2echo.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%:findBaseDirIF EXIST "%WDIR%"\.mvn goto baseDirFoundcd ..IF "%WDIR%"=="%CD%" goto baseDirNotFoundset WDIR=%CD%goto findBaseDir
:baseDirFoundset MAVEN_PROJECTBASEDIR=%WDIR%cd "%EXEC_DIR%"goto endDetectBaseDir
:baseDirNotFoundset MAVEN_PROJECTBASEDIR=%EXEC_DIR%cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansionfor /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)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central@REM This allows using the maven wrapper in projects that prohibit checking in binary data.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% )
powershell -Command "&{"^ "$webclient = new-object System.Net.WebClient;"^ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ "$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
@REM Provide a "standardized" way to retrieve the CLI args that will@REM work with both Windows and non-Windows executions.set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*if ERRORLEVEL 1 goto errorgoto end
:errorset ERROR_CODE=1
:end@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost@REM check for post script, once with legacy .bat ending and once with .cmd endingif exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd":skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112<?xml version="1.0" encoding="UTF-8"?><!--
Copyright (c), Eclipse Foundation, Inc. and its licensors.
All rights reserved.
This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0, which is available at https://www.eclipse.org/org/documents/edl-v10.php
SPDX-License-Identifier: BSD-3-Clause
--><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>jakarta.examples.tutorial.ejb.cart</groupId> <artifactId>cart</artifactId> <version>10-SNAPSHOT</version> <packaging>pom</packaging>
<name>cart</name>
<properties> <maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version> <maven.war.plugin.version>3.3.1</maven.war.plugin.version> <maven.ejb.plugin.version>3.1.0</maven.ejb.plugin.version> <maven.ear.plugin.version>3.1.0</maven.ear.plugin.version> <maven.acr.plugin.version>3.1.0</maven.acr.plugin.version> <maven.rar.plugin.version>2.4</maven.rar.plugin.version> <maven.exec.plugin.version>3.0.0</maven.exec.plugin.version> <liberty.maven.plugin.version>3.10.3</liberty.maven.plugin.version> <liberty.runtime.version>24.0.0.11</liberty.runtime.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jakarta.jakartaee-api.version>9.0.0</jakarta.jakartaee-api.version> </properties>
<modules> <module>cart-ejb</module> <module>cart-web</module> </modules>
<dependencies> <dependency> <groupId>jakarta.platform</groupId> <artifactId>jakarta.jakartaee-api</artifactId> <version>${jakarta.jakartaee-api.version}</version> <scope>provided</scope> </dependency> </dependencies>
<build> <finalName>${project.artifactId}</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>${maven.war.plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ejb-plugin</artifactId> <version>${maven.ejb.plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ear-plugin</artifactId> <version>${maven.ear.plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-acr-plugin</artifactId> <version>${maven.acr.plugin.version}</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>${maven.exec.plugin.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-rar-plugin</artifactId> <version>${maven.rar.plugin.version}</version> </plugin> <plugin> <groupId>io.openliberty.tools</groupId> <artifactId>liberty-maven-plugin</artifactId> <version>${liberty.maven.plugin.version}</version> </plugin> </plugins> </pluginManagement>
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> </plugins> </build>
</project>123456789101112131415#!/usr/bin/env bashset -euo pipefail
BASE_URL="${BASE_URL:-http://localhost:9080/cart}"
echo "Health check: ${BASE_URL}"HTTP_STATUS=$(curl -sL -o /dev/null -w "%{http_code}" "${BASE_URL}")
if [ "$HTTP_STATUS" -eq 200 ]; then echo "PASS - got HTTP ${HTTP_STATUS}" exit 0else echo "FAIL - got HTTP ${HTTP_STATUS}" exit 1fi1234567891011121314151617181920212223242526272829303132333435363738394041# VCS.git/
# Maven.mvn/**/.mvn/mvnwmvnw.cmd**/mvnw**/mvnw.cmdtarget/**/target/pom.xml.tagpom.xml.releaseBackuppom.xml.versionsBackuppom.xml.nextrelease.propertiesdependency-reduced-pom.xmlbuildNumber.properties
# IDE / Editor.vscode/**/.vscode/.zed/**/.zed/.idea/**/.idea/*.iml*.ipr*.iws
# OS.DS_Store**/.DS_StoreThumbs.dbehthumbs.db
# Logs / temp*.log*.tmp*.temp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117/* * 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 * * http://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(); }
}12distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zipwrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar123456789101112131415161718192021222324252627282930313233343536FROM maven:3.9.12-ibm-semeru-21-noble
USER root# install uvRUN apt-get update && apt-get install -y --no-install-recommends curl lsof python3-venv python3-full \ && curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"
# Shared browsers path so Chromium is cached onceENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwrightRUN mkdir -p /ms-playwright && chmod 755 /ms-playwright
# create venv and installRUN uv venv /opt/venv \ && uv pip install --python /opt/venv/bin/python playwright==1.47.0 pytest
ENV PATH="/opt/venv/bin:$PATH"RUN playwright install --with-deps chromium
WORKDIR /app
# Cache Maven dependencies separately from source (multi-module)COPY pom.xml .COPY cart-ejb/pom.xml cart-ejb/COPY cart-web/pom.xml cart-web/RUN mvn dependency:go-offline -q
# Build applicationCOPY . .RUN mvn install -pl cart-web -am -DskipTests -q
COPY test.sh .RUN chmod +x test.sh
CMD ["java", "-jar", "cart-web/target/quarkus-app/quarkus-run.jar"]123456789101112131415161718192021222324252627282930313233343536373839404142434445<?xml version="1.0" encoding="UTF-8"?><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>quarkus.examples.tutorial.cart</groupId> <artifactId>parent</artifactId> <version>1.0.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cart-ejb</artifactId> <name>cart-ejb</name>
<properties> <maven.compiler.release>17</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
<dependencies> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-arc</artifactId> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>io.smallrye</groupId> <artifactId>jandex-maven-plugin</artifactId> <version>3.5.0</version> <executions> <execution> <id>make-index</id> <goals> <goal>jandex</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
</project>1234567891011121314151617181920package quarkus.tutorial.cart.service;
import java.util.List;import quarkus.tutorial.cart.util.BookException;
public interface Cart { public void initialize(String person) throws BookException;
public void initialize( String person, String id) throws BookException;
public void addBook(String title);
public void removeBook(String title) throws BookException;
public List<String> getContents();
public void remove();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970package quarkus.tutorial.cart.service;
import java.io.Serializable;import java.util.ArrayList;import java.util.List;import jakarta.enterprise.context.SessionScoped;import quarkus.tutorial.cart.util.BookException;import quarkus.tutorial.cart.util.IdVerifier;
@SessionScopedpublic class CartBean implements Cart, Serializable {
String customerId; String customerName; List<String> contents = new ArrayList<>();
@Override public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; }
customerId = "0"; contents = new ArrayList<>(); }
@Override public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; }
IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); }
contents = new ArrayList<>(); }
@Override public void addBook(String title) { contents.add(title); }
@Override public void removeBook(String title) throws BookException { boolean result = contents.remove(title);
if (result == false) { throw new BookException("\"" + title + "\" not in cart."); } }
@Override public List<String> getContents() { return contents; }
@Override public void remove() { contents = new ArrayList<>(); }}1234567891011package quarkus.tutorial.cart.util;
public class BookException extends Exception { private static final long serialVersionUID = 6274585742564840905L;
public BookException() {}
public BookException(String msg) { super(msg); }}1234567891011121314151617package quarkus.tutorial.cart.util;
public class IdVerifier { public IdVerifier() {}
public boolean validate(String id) { boolean result = true;
for (int i = 0; i < id.length(); i++) { if (Character.isDigit(id.charAt(i)) == false) { result = false; } }
return result; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677<?xml version="1.0" encoding="UTF-8"?><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>quarkus.examples.tutorial.cart</groupId> <artifactId>parent</artifactId> <version>1.0.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cart-web</artifactId> <name>cart-web</name>
<properties> <maven.compiler.release>17</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
<dependencies> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-arc</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy-jackson</artifactId> </dependency> <!-- used to invalidate the session --> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-undertow</artifactId> </dependency>
<dependency> <groupId>quarkus.examples.tutorial.cart</groupId> <artifactId>cart-ejb</artifactId> <version>${project.version}</version> </dependency>
<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-junit5</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <scope>test</scope> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>${quarkus.platform.group-id}</groupId> <artifactId>quarkus-maven-plugin</artifactId> <extensions>true</extensions> <executions> <execution> <goals> <goal>build</goal> <goal>generate-code</goal> <goal>generate-code-tests</goal> <goal>native-image-agent</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
</project>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798##### This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode## Before building the container image run:## ./mvnw package## Then, build the image with:## docker build -f src/main/docker/Dockerfile.jvm -t quarkus/cart-jvm .## Then run the container using:## docker run -i --rm -p 8080:8080 quarkus/cart-jvm## If you want to include the debug port into your docker image# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005# when running the container## Then run the container using :## docker run -i --rm -p 8080:8080 quarkus/cart-jvm## This image uses the `run-java.sh` script to run the application.# This scripts computes the command line to execute your Java application, and# includes memory/GC tuning.# You can configure the behavior using the following environment properties:# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override# the default JVM options, use `JAVA_OPTS_APPEND` to append options# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options# in JAVA_OPTS (example: "-Dsome.property=foo")# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is# used to calculate a default maximal heap memory based on a containers restriction.# If used in a container without any memory constraints for the container then this# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio# of the container available memory as set here. The default is `50` which means 50%# of the available memory is used as an upper boundary. You can skip this mechanism by# setting this value to `0` in which case no `-Xmx` option is added.# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This# is used to calculate a default initial heap memory based on the maximum heap memory.# If used in a container without any memory constraints for the container then this# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`# is used as the initial heap size. You can skip this mechanism by setting this value# to `0` in which case no `-Xms` option is added (example: "25")# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.# This is used to calculate the maximum value of the initial heap memory. If used in# a container without any memory constraints for the container then this option has# no effect. If there is a memory constraint then `-Xms` is limited to the value set# here. The default is 4096MB which means the calculated value of `-Xms` never will# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output# when things are happening. This option, if set to true, will set# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:# true").# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").# - CONTAINER_CORE_LIMIT: A calculated core limit as described in# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.# (example: "20")# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.# (example: "40")# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.# (example: "4")# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus# previous GC times. (example: "90")# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should# contain the necessary JRE command-line options to specify the required GC, which# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be# accessed directly. (example: "foo.example.com,bar.example.com")####FROM registry.access.redhat.com/ubi9/openjdk-21:1.23
ENV LANGUAGE='en_US:en'
# We make four distinct layers so if there are application changes the library layers can be re-usedCOPY --chown=185 target/quarkus-app/lib/ /deployments/lib/COPY --chown=185 target/quarkus-app/*.jar /deployments/COPY --chown=185 target/quarkus-app/app/ /deployments/app/COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/
EXPOSE 8080USER 185ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394##### This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode## Before building the container image run:## ./mvnw package -Dquarkus.package.jar.type=legacy-jar## Then, build the image with:## docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/cart-legacy-jar .## Then run the container using:## docker run -i --rm -p 8080:8080 quarkus/cart-legacy-jar## If you want to include the debug port into your docker image# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005# when running the container## Then run the container using :## docker run -i --rm -p 8080:8080 quarkus/cart-legacy-jar## This image uses the `run-java.sh` script to run the application.# This scripts computes the command line to execute your Java application, and# includes memory/GC tuning.# You can configure the behavior using the following environment properties:# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override# the default JVM options, use `JAVA_OPTS_APPEND` to append options# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options# in JAVA_OPTS (example: "-Dsome.property=foo")# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is# used to calculate a default maximal heap memory based on a containers restriction.# If used in a container without any memory constraints for the container then this# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio# of the container available memory as set here. The default is `50` which means 50%# of the available memory is used as an upper boundary. You can skip this mechanism by# setting this value to `0` in which case no `-Xmx` option is added.# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This# is used to calculate a default initial heap memory based on the maximum heap memory.# If used in a container without any memory constraints for the container then this# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`# is used as the initial heap size. You can skip this mechanism by setting this value# to `0` in which case no `-Xms` option is added (example: "25")# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.# This is used to calculate the maximum value of the initial heap memory. If used in# a container without any memory constraints for the container then this option has# no effect. If there is a memory constraint then `-Xms` is limited to the value set# here. The default is 4096MB which means the calculated value of `-Xms` never will# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output# when things are happening. This option, if set to true, will set# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:# true").# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").# - CONTAINER_CORE_LIMIT: A calculated core limit as described in# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.# (example: "20")# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.# (example: "40")# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.# (example: "4")# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus# previous GC times. (example: "90")# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should# contain the necessary JRE command-line options to specify the required GC, which# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be# accessed directly. (example: "foo.example.com,bar.example.com")####FROM registry.access.redhat.com/ubi9/openjdk-21:1.23
ENV LANGUAGE='en_US:en'
COPY target/lib/* /deployments/lib/COPY target/*-runner.jar /deployments/quarkus-run.jar
EXPOSE 8080USER 185ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]1234567891011121314151617181920212223242526272829##### This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode.## Before building the container image run:## ./mvnw package -Dnative## Then, build the image with:## docker build -f src/main/docker/Dockerfile.native -t quarkus/cart .## Then run the container using:## docker run -i --rm -p 8080:8080 quarkus/cart## The ` registry.access.redhat.com/ubi9/ubi-minimal:9.6` base image is based on UBI 9.# To use UBI 8, switch to `quay.io/ubi8/ubi-minimal:8.10`.###FROM registry.access.redhat.com/ubi9/ubi-minimal:9.6WORKDIR /work/RUN chown 1001 /work \ && chmod "g+rwX" /work \ && chown 1001:root /workCOPY --chown=1001:root --chmod=0755 target/*-runner /work/application
EXPOSE 8080USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]1234567891011121314151617181920212223242526272829303132##### This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode.# It uses a micro base image, tuned for Quarkus native executables.# It reduces the size of the resulting container image.# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image.## Before building the container image run:## ./mvnw package -Dnative## Then, build the image with:## docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/cart .## Then run the container using:## docker run -i --rm -p 8080:8080 quarkus/cart## The `quay.io/quarkus/ubi9-quarkus-micro-image:2.0` base image is based on UBI 9.# To use UBI 8, switch to `quay.io/quarkus/quarkus-micro-image:2.0`.###FROM quay.io/quarkus/ubi9-quarkus-micro-image:2.0WORKDIR /work/RUN chown 1001 /work \ && chmod "g+rwX" /work \ && chown 1001:root /workCOPY --chown=1001:root --chmod=0755 target/*-runner /work/application
EXPOSE 8080USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174package quarkus.tutorial.cart;
import java.util.HashMap;import java.util.List;import java.util.Map;import jakarta.enterprise.context.RequestScoped;import jakarta.inject.Inject;import jakarta.servlet.http.HttpServletRequest;import jakarta.ws.rs.Consumes;import jakarta.ws.rs.DELETE;import jakarta.ws.rs.GET;import jakarta.ws.rs.POST;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;import quarkus.tutorial.cart.service.Cart;import quarkus.tutorial.cart.util.BookException;
/** * REST resource for cart operations. * * Provides HTTP endpoints to interact with the shopping cart EJB. */@Path("/api/cart")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)@RequestScopedpublic class CartResource {
@Inject Cart cart;
/** * Initialize a new cart session. * * POST /api/cart/initialize * * Body: {"customerName": "John Doe", "customerId": "123"} */ @POST @Path("/initialize") public Response initializeCart(CustomerRequest request) { try { if (request.customerId != null && !request.customerId.isEmpty()) { cart.initialize(request.customerName, request.customerId); } else { cart.initialize(request.customerName); }
Map<String, String> response = new HashMap<>(); response.put("message", "Cart initialized successfully"); response.put("customerName", request.customerName);
return Response.ok(response).build(); } catch (BookException e) { return Response.status(Response.Status.BAD_REQUEST) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Add a book to the cart. * * POST /api/cart/books/{title} */ @POST @Path("/books/{title}") public Response addBook(@PathParam("title") String title) { try { cart.addBook(title);
Map<String, Object> response = new HashMap<>(); response.put("message", "Book added successfully"); response.put("title", title); response.put("cartSize", cart.getContents().size());
return Response.ok(response).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Remove a book from the cart. * * DELETE /api/cart/books/{title} */ @DELETE @Path("/books/{title}") public Response removeBook(@PathParam("title") String title) { try { cart.removeBook(title);
Map<String, Object> response = new HashMap<>(); response.put("message", "Book removed successfully"); response.put("title", title); response.put("cartSize", cart.getContents().size());
return Response.ok(response).build(); } catch (BookException e) { return Response.status(Response.Status.NOT_FOUND) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Get all books in the cart. * * GET /api/cart/books */ @GET @Path("/books") public Response getBooks() { try { List<String> contents = cart.getContents();
Map<String, Object> response = new HashMap<>(); response.put("books", contents); response.put("count", contents.size());
return Response.ok(response).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Clear the cart and end the session. * * DELETE /api/cart */ @DELETE public Response clearCart(@Context HttpServletRequest request) { try { // Simulate EJB @Remove by clearing the session and destroying the bean var session = request.getSession(false); if (session != null) { session.invalidate(); }
return Response.ok(Map.of("message", "Cart cleared successfully")).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(Map.of("error", e.getMessage())) .build(); } }
/** * Health check endpoint. * * GET /api/cart/health */ @GET @Path("/health") public Response health() { return Response.ok(Map.of("status", "UP", "service", "cart-api")).build(); }
// Request/Response DTOs public static class CustomerRequest { public String customerName; public String customerId; }}1quarkus.http.root-path=/cart123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332#!/bin/sh# ----------------------------------------------------------------------------# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# 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## http://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.# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------# Apache Maven Wrapper startup batch script, version 3.3.2## Required ENV vars:# ------------------# JAVA_HOME - location of a JDK home dir## Optional ENV vars# -----------------# MAVEN_OPTS - parameters passed to the Java VM when running Maven# e.g. to debug Maven itself, use# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000# MAVEN_SKIP_RC - flag to disable loading of mavenrc files# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ]; then
if [ -f /usr/local/etc/mavenrc ]; then . /usr/local/etc/mavenrc fi
if [ -f /etc/mavenrc ]; then . /etc/mavenrc fi
if [ -f "$HOME/.mavenrc" ]; then . "$HOME/.mavenrc" fi
fi
# OS specific support. $var _must_ be set to either true or false.cygwin=falsedarwin=falsemingw=falsecase "$(uname)" inCYGWIN*) 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 JAVA_HOME="$(/usr/libexec/java_home)" export JAVA_HOME else JAVA_HOME="/Library/Java/Home" export JAVA_HOME fi fi ;;esac
if [ -z "$JAVA_HOME" ]; then if [ -r /etc/gentoo-release ]; then JAVA_HOME=$(java-config --jre-home) fifi
# For Cygwin, ensure paths are in UNIX format before anything is touchedif $cygwin; then [ -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 touchedif $mingw; then [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] \ && JAVA_HOME="$( cd "$JAVA_HOME" || ( echo "cannot cd into $JAVA_HOME." >&2 exit 1 ) 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 fifi
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 else JAVACMD="$( \unset -f command 2>/dev/null \command -v java )" fifi
if [ ! -x "$JAVACMD" ]; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1fi
if [ -z "$JAVA_HOME" ]; then echo "Warning: JAVA_HOME environment variable is not set." >&2fi
# traverses directory structure from process work directory to filesystem root# first directory with .mvn subdirectory is considered project base directoryfind_maven_basedir() { if [ -z "$1" ]; then echo "Path not specified to find_maven_basedir" >&2 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/.." || exit 1 pwd ) fi # end of workaround done printf '%s' "$( cd "$basedir" || exit 1 pwd )"}
# concatenates all lines of a fileconcat_lines() { if [ -f "$1" ]; then # Remove \r in case we run on Windows within Git Bash # and check out the repository with auto CRLF management # enabled. Otherwise, we may read lines that are delimited with # \r\n and produce $'-Xarg\r' rather than -Xarg due to word # splitting rules. tr -s '\r\n' ' ' <"$1" fi}
log() { if [ "$MVNW_VERBOSE" = true ]; then printf '%s\n' "$1" fi}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")if [ -z "$BASE_DIR" ]; then exit 1fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}export MAVEN_PROJECTBASEDIRlog "$MAVEN_PROJECTBASEDIR"
########################################################################################### 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.##########################################################################################wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"if [ -r "$wrapperJarPath" ]; then log "Found $wrapperJarPath"else log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" else wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" fi while IFS="=" read -r key value; do # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) safeValue=$(echo "$value" | tr -d '\r') case "$key" in wrapperUrl) wrapperUrl="$safeValue" break ;; esac done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" log "Downloading from: $wrapperUrl"
if $cygwin; then wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") fi
if command -v wget >/dev/null; then log "Found wget ... using wget" [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi elif command -v curl >/dev/null; then log "Found curl ... using curl" [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" else curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" fi else log "Falling back to using Java to download" javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" # For Cygwin, switch paths to Windows format before running javac if $cygwin; then javaSource=$(cygpath --path --windows "$javaSource") javaClass=$(cygpath --path --windows "$javaClass") fi if [ -e "$javaSource" ]; then if [ ! -e "$javaClass" ]; then log " - Compiling MavenWrapperDownloader.java ..." ("$JAVA_HOME/bin/javac" "$javaSource") fi if [ -e "$javaClass" ]; then log " - Running MavenWrapperDownloader.java ..." ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" fi fi fifi########################################################################################### End of extension##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar filewrapperSha256Sum=""while IFS="=" read -r key value; do case "$key" in wrapperSha256Sum) wrapperSha256Sum=$value break ;; esacdone <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"if [ -n "$wrapperSha256Sum" ]; then wrapperSha256Result=false if command -v sha256sum >/dev/null; then if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c >/dev/null 2>&1; then wrapperSha256Result=true fi elif command -v shasum >/dev/null; then if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c >/dev/null 2>&1; then wrapperSha256Result=true fi else echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." >&2 exit 1 fi if [ $wrapperSha256Result = false ]; then echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 exit 1 fifi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running javaif $cygwin; then [ -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
# shellcheck disable=SC2086 # safe argsexec "$JAVACMD" \ $MAVEN_OPTS \ $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206@REM ----------------------------------------------------------------------------@REM Licensed to the Apache Software Foundation (ASF) under one@REM or more contributor license agreements. See the NOTICE file@REM distributed with this work for additional information@REM regarding copyright ownership. The ASF licenses this file@REM to you under the Apache License, Version 2.0 (the@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@REM http://www.apache.org/licenses/LICENSE-2.0@REM@REM Unless required by applicable law or agreed to in writing,@REM software distributed under the License is distributed on an@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@REM KIND, either express or implied. See the License for the@REM specific language governing permissions and limitations@REM under the License.@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------@REM Apache Maven Wrapper startup batch script, version 3.3.2@REM@REM Required ENV vars:@REM JAVA_HOME - location of a JDK home dir@REM@REM Optional ENV vars@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands@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 Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'@echo off@REM set title of command windowtitle %0@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOMEif "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this oneif not "%MAVEN_SKIP_RC%" == "" goto skipRcPre@REM check for pre script, once with legacy .bat ending and once with .cmd endingif exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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. >&2echo Error: JAVA_HOME not found in your environment. >&2echo Please set the JAVA_HOME variable in your environment to match the >&2echo location of your Java installation. >&2echo. >&2goto error
:OkJHomeif exist "%JAVA_HOME%\bin\java.exe" goto init
echo. >&2echo Error: JAVA_HOME is set to an invalid directory. >&2echo JAVA_HOME = "%JAVA_HOME%" >&2echo Please set the JAVA_HOME variable in your environment to match the >&2echo location of your Java installation. >&2echo. >&2goto 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%:findBaseDirIF EXIST "%WDIR%"\.mvn goto baseDirFoundcd ..IF "%WDIR%"=="%CD%" goto baseDirNotFoundset WDIR=%CD%goto findBaseDir
:baseDirFoundset MAVEN_PROJECTBASEDIR=%WDIR%cd "%EXEC_DIR%"goto endDetectBaseDir
:baseDirNotFoundset MAVEN_PROJECTBASEDIR=%EXEC_DIR%cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansionfor /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 WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central@REM This allows using the maven wrapper in projects that prohibit checking in binary data.if exist %WRAPPER_JAR% ( if "%MVNW_VERBOSE%" == "true" ( echo Found %WRAPPER_JAR% )) else ( if not "%MVNW_REPOURL%" == "" ( SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" ) if "%MVNW_VERBOSE%" == "true" ( echo Couldn't find %WRAPPER_JAR%, downloading it ... echo Downloading from: %WRAPPER_URL% )
powershell -Command "&{"^ "$webclient = new-object System.Net.WebClient;"^ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ "}"^ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ "}" if "%MVNW_VERBOSE%" == "true" ( echo Finished downloading %WRAPPER_JAR% ))@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar fileSET WRAPPER_SHA_256_SUM=""FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B)IF NOT %WRAPPER_SHA_256_SUM%=="" ( powershell -Command "&{"^ "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ " exit 1;"^ "}"^ "}" if ERRORLEVEL 1 goto error)
@REM Provide a "standardized" way to retrieve the CLI args that will@REM work with both Windows and non-Windows executions.set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^ %JVM_CONFIG_MAVEN_PROPS% ^ %MAVEN_OPTS% ^ %MAVEN_DEBUG_OPTS% ^ -classpath %WRAPPER_JAR% ^ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*if ERRORLEVEL 1 goto errorgoto end
:errorset ERROR_CODE=1
:end@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost@REM check for post script, once with legacy .bat ending and once with .cmd endingif exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd":skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102<?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"> <modelVersion>4.0.0</modelVersion> <groupId>quarkus.examples.tutorial.cart</groupId> <artifactId>parent</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>pom</packaging>
<properties> <compiler-plugin.version>3.14.0</compiler-plugin.version> <maven.compiler.release>21</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id> <quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id> <quarkus.platform.version>3.30.5</quarkus.platform.version> <skipITs>true</skipITs> <surefire-plugin.version>3.5.3</surefire-plugin.version> </properties>
<modules> <module>cart-ejb</module> <module>cart-web</module> </modules>
<dependencyManagement> <dependencies> <dependency> <groupId>${quarkus.platform.group-id}</groupId> <artifactId>${quarkus.platform.artifact-id}</artifactId> <version>${quarkus.platform.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
<build> <pluginManagement> <plugins> <plugin> <groupId>${quarkus.platform.group-id}</groupId> <artifactId>quarkus-maven-plugin</artifactId> <version>${quarkus.platform.version}</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>${compiler-plugin.version}</version> <configuration> <parameters>true</parameters> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>${surefire-plugin.version}</version> <configuration> <systemPropertyVariables> <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> <maven.home>${maven.home}</maven.home> </systemPropertyVariables> </configuration> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>${surefire-plugin.version}</version> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> <configuration> <systemPropertyVariables> <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path> <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> <maven.home>${maven.home}</maven.home> </systemPropertyVariables> </configuration> </plugin> </plugins> </build>
<profiles> <profile> <id>native</id> <activation> <property> <name>native</name> </property> </activation> <properties> <skipITs>false</skipITs> <quarkus.native.enabled>true</quarkus.native.enabled> </properties> </profile> </profiles></project>123456789101112131415#!/usr/bin/env bashset -euo pipefail
BASE_URL="${BASE_URL:-http://localhost:8080/cart}"
echo "Health check: ${BASE_URL}"HTTP_STATUS=$(curl -sL -o /dev/null -w "%{http_code}" "${BASE_URL}")
if [ "$HTTP_STATUS" -eq 200 ]; then echo "PASS - got HTTP ${HTTP_STATUS}" exit 0else echo "FAIL - got HTTP ${HTTP_STATUS}" exit 1fi1234567891011121314151617181920212223242526272829303132333435363738394041# VCS.git/
# Maven.mvn/**/.mvn/mvnwmvnw.cmd**/mvnw**/mvnw.cmdtarget/**/target/pom.xml.tagpom.xml.releaseBackuppom.xml.versionsBackuppom.xml.nextrelease.propertiesdependency-reduced-pom.xmlbuildNumber.properties
# IDE / Editor.vscode/**/.vscode/.zed/**/.zed/.idea/**/.idea/*.iml*.ipr*.iws
# OS.DS_Store**/.DS_StoreThumbs.dbehthumbs.db
# Logs / temp*.log*.tmp*.temp123wrapperVersion=3.3.4distributionType=only-scriptdistributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip123456789101112131415161718192021222324252627282930313233343536FROM maven:3.9.12-ibm-semeru-21-noble
USER root# install uvRUN apt-get update && apt-get install -y --no-install-recommends curl python3-venv python3-full \ && curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"
# Shared browsers path so Chromium is cached onceENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwrightRUN mkdir -p /ms-playwright && chmod 755 /ms-playwright
# create venv and installRUN uv venv /opt/venv \ && uv pip install --python /opt/venv/bin/python playwright==1.47.0 pytest
ENV PATH="/opt/venv/bin:$PATH"RUN playwright install --with-deps chromium
WORKDIR /app
# Cache Maven dependencies separately from source (multi-module)COPY pom.xml .COPY cart-ejb/pom.xml cart-ejb/COPY cart-web/pom.xml cart-web/RUN mvn dependency:go-offline -q
# Build applicationCOPY . .RUN mvn install -DskipTests -q
COPY test.sh .RUN chmod +x test.sh
CMD ["mvn", "spring-boot:run", "-pl", "cart-web"]1234567891011121314151617181920212223242526272829<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>spring.examples.tutorial.cart</groupId> <artifactId>parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cart-ejb</artifactId> <packaging>jar</packaging>
<properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies></project>123456789101112131415161718192021
package spring.examples.tutorial.cart.service;
import java.util.List;import spring.examples.tutorial.cart.util.BookException;
public interface Cart { public void initialize(String person) throws BookException;
public void initialize( String person, String id) throws BookException;
public void addBook(String title);
public void removeBook(String title) throws BookException;
public List<String> getContents();
public void remove();}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768package spring.examples.tutorial.cart.service;
import org.springframework.context.annotation.Scope;import org.springframework.context.annotation.ScopedProxyMode;import org.springframework.stereotype.Service;import spring.examples.tutorial.cart.util.BookException;import spring.examples.tutorial.cart.util.IdVerifier;import java.util.ArrayList;import java.util.List;
@Service@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)public class CartServiceImpl implements Cart {
private String customerId; private String customerName; private List<String> contents = new ArrayList<>();
@Override public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } customerName = person; customerId = "0"; contents = new ArrayList<>(); }
@Override public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } customerName = person;
IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); }
contents = new ArrayList<>(); }
@Override public void addBook(String title) { contents.add(title); }
@Override public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (!result) { throw new BookException("\"" + title + "\" not in cart."); } }
@Override public List<String> getContents() { return contents; }
@Override public void remove() { contents = new ArrayList<>(); }}1234567891011package spring.examples.tutorial.cart.util;
public class BookException extends Exception { private static final long serialVersionUID = 6274585742564840905L;
public BookException() {}
public BookException(String msg) { super(msg); }}1234567891011121314151617package spring.examples.tutorial.cart.util;
public class IdVerifier { public IdVerifier() {}
public boolean validate(String id) { boolean result = true;
for (int i = 0; i < id.length(); i++) { if (Character.isDigit(id.charAt(i)) == false) { result = false; } }
return result; }}.gitignoreAdded+94
CONTRIBUTING.mdAdded+1098
README.md+250-1
benchmark/business_domain/cart/jakarta/.dockerignoreAdded+41
benchmark/business_domain/cart/jakarta/.mvn/wrapper/MavenWrapperDownloader.javaAdded+117
benchmark/business_domain/cart/jakarta/.mvn/wrapper/maven-wrapper.propertiesAdded+2
benchmark/business_domain/cart/jakarta/DockerfileAdded+36
benchmark/business_domain/cart/jakarta/cart-ejb/pom.xmlAdded+36
benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/ejb/Cart.javaAdded+36
benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/ejb/CartBean.javaAdded+82
benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/util/BookException.javaAdded+22
benchmark/business_domain/cart/jakarta/cart-ejb/src/main/java/jakarta/tutorial/cart/util/IdVerifier.javaAdded+29
benchmark/business_domain/cart/jakarta/cart-ejb/src/main/resources/META-INF/MANIFEST.MFAdded+2
benchmark/business_domain/cart/jakarta/cart-web/pom.xmlAdded+82
benchmark/business_domain/cart/jakarta/cart-web/src/main/java/jakarta/tutorial/cart/web/CartResource.javaAdded+173
benchmark/business_domain/cart/jakarta/cart-web/src/main/java/jakarta/tutorial/cart/web/RestApplication.javaAdded+25
benchmark/business_domain/cart/jakarta/cart-web/src/main/liberty/config/server.xmlAdded+46
benchmark/business_domain/cart/jakarta/cart-web/src/main/webapp/WEB-INF/beans.xmlAdded+7
benchmark/business_domain/cart/jakarta/mvnwAdded+310
benchmark/business_domain/cart/jakarta/mvnw.cmdAdded+182
benchmark/business_domain/cart/jakarta/pom.xmlAdded+112
benchmark/business_domain/cart/jakarta/test.shAdded+15
benchmark/business_domain/cart/quarkus/.dockerignoreAdded+41
benchmark/business_domain/cart/quarkus/.mvn/wrapper/MavenWrapperDownloader.javaAdded+117
benchmark/business_domain/cart/quarkus/.mvn/wrapper/maven-wrapper.propertiesAdded+2
benchmark/business_domain/cart/quarkus/DockerfileAdded+36
benchmark/business_domain/cart/quarkus/cart-ejb/pom.xmlAdded+45
benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/service/Cart.javaAdded+20
benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/service/CartBean.javaAdded+70
benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/util/BookException.javaAdded+11
benchmark/business_domain/cart/quarkus/cart-ejb/src/main/java/quarkus/tutorial/cart/util/IdVerifier.javaAdded+17
benchmark/business_domain/cart/quarkus/cart-web/pom.xmlAdded+77
benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.jvmAdded+98
benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.legacy-jarAdded+94
benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.nativeAdded+29
benchmark/business_domain/cart/quarkus/cart-web/src/main/docker/Dockerfile.native-microAdded+32
benchmark/business_domain/cart/quarkus/cart-web/src/main/java/quarkus/tutorial/cart/CartResource.javaAdded+174
benchmark/business_domain/cart/quarkus/cart-web/src/main/resources/application.propertiesAdded+1
benchmark/business_domain/cart/quarkus/mvnwAdded+332
benchmark/business_domain/cart/quarkus/mvnw.cmdAdded+206
benchmark/business_domain/cart/quarkus/pom.xmlAdded+102
benchmark/business_domain/cart/quarkus/test.shAdded+15
benchmark/business_domain/cart/spring/.dockerignoreAdded+41
benchmark/business_domain/cart/spring/.mvn/wrapper/maven-wrapper.propertiesAdded+3
benchmark/business_domain/cart/spring/DockerfileAdded+36
benchmark/business_domain/cart/spring/cart-ejb/pom.xmlAdded+29
benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/service/Cart.javaAdded+21
benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/service/CartServiceImpl.javaAdded+68
benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/util/BookException.javaAdded+11
benchmark/business_domain/cart/spring/cart-ejb/src/main/java/spring/examples/tutorial/cart/util/IdVerifier.javaAdded+17