From 5dbc913a3feb887fafbf9972220d24d7115694f7 Mon Sep 17 00:00:00 2001 From: Money Yu Date: Thu, 3 Sep 2026 02:02:20 +0800 Subject: [PATCH] feat(java): add SimpleWeb Java edition with build and VM deploy workflows SimpleWeb only shipped an ASP.NET Core edition, so the same DevOps practices could not be demonstrated on a second technology stack. Add a Java edition that lives next to the C# one and is built and deployed independently. - Add src-java/, a Spring Boot 4.1.1 / Java 21 application (Maven project root with wrapper and Dockerfile) serving /, /api/info, /actuator/health and /actuator/info, packaged as target/simpleweb.jar - Add .github/workflows/12.java-build.yml: runs ./mvnw -B verify on pushes that touch src-java/**, uploads the deployable jar and writes a job summary - Add .github/workflows/13.java-vm-deploy.yml: manual-only deployment to a Linux VM for the test or production GitHub Environment, using OIDC login and az vm run-command, with contents:write scoped to the publishing job only, a DEPLOY_OK sentinel check and a buildSha-verifying smoke test - Document the Java edition in src-java/README.md and link it from README.md and README_zh-TW.md without touching the existing C# documentation - Ignore Maven build output and Java IDE files Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1b3fad4e-252e-4b4b-8de7-618fddc6979f --- .github/workflows/12.java-build.yml | 56 ++++ .github/workflows/13.java-vm-deploy.yml | 186 +++++++++++ .gitignore | 10 +- README.md | 42 ++- README_zh-TW.md | 39 ++- src-java/.gitattributes | 5 + .../.mvn/wrapper/maven-wrapper.properties | 3 + src-java/Dockerfile | 24 ++ src-java/README.md | 188 +++++++++++ src-java/mvnw | 295 ++++++++++++++++++ src-java/mvnw.cmd | 189 +++++++++++ src-java/pom.xml | 78 +++++ .../gh200/simpleweb/SimpleWebApplication.java | 12 + .../money/gh200/simpleweb/model/AppInfo.java | 15 + .../gh200/simpleweb/service/InfoService.java | 131 ++++++++ .../gh200/simpleweb/web/HomeController.java | 24 ++ .../simpleweb/web/InfoApiController.java | 22 ++ src-java/src/main/resources/application.yml | 23 ++ .../src/main/resources/static/css/site.css | 139 +++++++++ .../src/main/resources/templates/index.html | 57 ++++ .../simpleweb/SimpleWebApplicationIT.java | 73 +++++ .../simpleweb/service/InfoServiceTest.java | 87 ++++++ .../simpleweb/web/HomeControllerTest.java | 42 +++ 23 files changed, 1737 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/12.java-build.yml create mode 100644 .github/workflows/13.java-vm-deploy.yml create mode 100644 src-java/.gitattributes create mode 100644 src-java/.mvn/wrapper/maven-wrapper.properties create mode 100644 src-java/Dockerfile create mode 100644 src-java/README.md create mode 100755 src-java/mvnw create mode 100644 src-java/mvnw.cmd create mode 100644 src-java/pom.xml create mode 100644 src-java/src/main/java/money/gh200/simpleweb/SimpleWebApplication.java create mode 100644 src-java/src/main/java/money/gh200/simpleweb/model/AppInfo.java create mode 100644 src-java/src/main/java/money/gh200/simpleweb/service/InfoService.java create mode 100644 src-java/src/main/java/money/gh200/simpleweb/web/HomeController.java create mode 100644 src-java/src/main/java/money/gh200/simpleweb/web/InfoApiController.java create mode 100644 src-java/src/main/resources/application.yml create mode 100644 src-java/src/main/resources/static/css/site.css create mode 100644 src-java/src/main/resources/templates/index.html create mode 100644 src-java/src/test/java/money/gh200/simpleweb/SimpleWebApplicationIT.java create mode 100644 src-java/src/test/java/money/gh200/simpleweb/service/InfoServiceTest.java create mode 100644 src-java/src/test/java/money/gh200/simpleweb/web/HomeControllerTest.java diff --git a/.github/workflows/12.java-build.yml b/.github/workflows/12.java-build.yml new file mode 100644 index 0000000..198a2d5 --- /dev/null +++ b/.github/workflows/12.java-build.yml @@ -0,0 +1,56 @@ +# 12 - Java Edition:建置與測試(CI) +# +# 教學重點 +# - paths 過濾:只有 src-java/** 有變更時才跑,避免 C# 的變更觸發 Java CI +# - setup-java 的 cache: maven 就足以加速相依套件下載,不需要自己寫 actions/cache +# - Artifact 只上傳「要部署的那一個檔案」(src-java/target/simpleweb.jar), +# 不要把整個 target/ 丟上去 +name: 12.java-build + +on: + push: + paths: + - 'src-java/**' + - '.github/workflows/12.java-build.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + cache: maven + cache-dependency-path: src-java/pom.xml + + - name: Build and test + working-directory: src-java + run: ./mvnw -B verify + + # if-no-files-found: error → finalName 若被改掉,這裡會直接失敗而不是靜靜地上傳空的 artifact + - name: Upload deployable jar + uses: actions/upload-artifact@v7 + with: + name: simpleweb-jar + path: src-java/target/simpleweb.jar + if-no-files-found: error + retention-days: 7 + + - name: Write job summary + run: | + { + echo "## SimpleWeb Java Edition" + echo "" + echo "- 產出物:\`src-java/target/simpleweb.jar\`" + echo "- 大小:$(du -h src-java/target/simpleweb.jar | cut -f1)" + echo "- SHA256:\`$(sha256sum src-java/target/simpleweb.jar | cut -d' ' -f1)\`" + echo "- 來源 commit:\`${GITHUB_SHA:0:7}\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/13.java-vm-deploy.yml b/.github/workflows/13.java-vm-deploy.yml new file mode 100644 index 0000000..8984dd7 --- /dev/null +++ b/.github/workflows/13.java-vm-deploy.yml @@ -0,0 +1,186 @@ +# 13 - Java Edition:部署到 VM(手動觸發) +# +# 教學重點 +# - 只用 workflow_dispatch:部署是「人決定什麼時候做」的動作,不要綁在 push 上 +# - environment 由執行時輸入的參數決定;正式環境的保護(required reviewers、 +# wait timer、限制分支)請在 GitHub Environment 設定,不要寫死在 workflow 裡 +# - permissions 分 job 給:build 需要 contents: write(發佈 Release asset), +# deploy 只需要 contents: read + id-token: write(OIDC) +# - az vm run-command:不用開 SSH port、不用保管私鑰就能在 VM 上執行指令 +# +# 部署載荷怎麼上 VM? +# 把 jar 發佈成「滾動式」的 public pre-release asset,VM 端用 curl 匿名下載, +# 不需要額外的儲存體或憑證。(私有 repo 請改用 SAS URL 或自架儲存體。) +# +# 執行前需要設定(Repository 或 Environment 層級): +# variables:AZURE_RESOURCE_GROUP、AZURE_VM_NAME、VM_PUBLIC_IP +# secrets :AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_SUBSCRIPTION_ID +# VM 端 :simpleweb 使用者、/opt/simpleweb/{test,prod} 目錄、 +# simpleweb-test / simpleweb-prod 兩個 systemd unit +# (unit 需 EnvironmentFile=/opt/simpleweb//app.env) +name: 13.java-vm-deploy + +on: + workflow_dispatch: + inputs: + environment: + description: 要部署的環境 + type: choice + required: true + default: test + options: + - test + - production + +permissions: + contents: read + +# 滾動式 asset 只有一份,同時跑兩個部署會互相覆蓋;用 concurrency 讓部署一次只跑一個。 +# cancel-in-progress: false → 排隊等前一個做完,不要把部署到一半的 run 砍掉。 +concurrency: + group: java-vm-deploy + cancel-in-progress: false + +env: + RELEASE_TAG: java-build-latest + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: write # 只有這個 job 需要寫入權限,用來發佈 Release asset + + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + cache: maven + cache-dependency-path: src-java/pom.xml + + - name: Build and test + working-directory: src-java + run: ./mvnw -B verify + + # 滾動式 pre-release:tag 固定,asset 每次覆蓋,VM 端的下載網址永遠一樣 + - name: Publish deployable + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: | + gh release view "$RELEASE_TAG" >/dev/null 2>&1 \ + || gh release create "$RELEASE_TAG" --prerelease \ + --title "SimpleWeb Java rolling build" \ + --notes "由 13.java-vm-deploy 自動更新的最新可部署版本" + gh release upload "$RELEASE_TAG" src-java/target/simpleweb.jar --clobber + + deploy: + runs-on: ubuntu-latest + needs: build + permissions: + contents: read + id-token: write # OIDC 換發 token 必要!少了這行 azure/login 一定失敗 + # 這一行讓 run 出現在 Environments 頁面,也是套用保護規則的依據。 + # 選 production 時若設了 required reviewers,job 會停在 Waiting 等人核准。 + environment: + name: ${{ inputs.environment }} + url: http://${{ vars.VM_PUBLIC_IP }}:${{ inputs.environment == 'production' && '8081' || '8080' }} + env: + APP_DIR: ${{ inputs.environment == 'production' && '/opt/simpleweb/prod' || '/opt/simpleweb/test' }} + SERVICE_NAME: ${{ inputs.environment == 'production' && 'simpleweb-prod' || 'simpleweb-test' }} + APP_PORT: ${{ inputs.environment == 'production' && '8081' || '8080' }} + APP_ENVIRONMENT: ${{ inputs.environment }} + + steps: + # 先確認設定齊全,錯誤訊息比「az 指令跑到一半失敗」清楚很多 + - name: Check required configuration + env: + AZURE_RESOURCE_GROUP: ${{ vars.AZURE_RESOURCE_GROUP }} + AZURE_VM_NAME: ${{ vars.AZURE_VM_NAME }} + VM_PUBLIC_IP: ${{ vars.VM_PUBLIC_IP }} + run: | + set -eu + missing='' + for name in AZURE_RESOURCE_GROUP AZURE_VM_NAME VM_PUBLIC_IP; do + eval "value=\${$name:-}" + [ -n "$value" ] || missing="$missing $name" + done + if [ -n "$missing" ]; then + echo "缺少必要的 variables:$missing" >&2 + exit 1 + fi + + # 使用 OIDC 登入 Azure(GitHub 這邊不需要存任何長期的 Azure 密碼) + - name: Azure login (OIDC) + uses: azure/login@v3 + with: + client-id: ${{ secrets.AZURE_CLIENT_ID }} + tenant-id: ${{ secrets.AZURE_TENANT_ID }} + subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} + + # 訓練用訂閱常有 auto-shutdown;部署前先確保 VM 正在執行 + - name: Ensure VM is running + run: | + az vm start \ + --resource-group "${{ vars.AZURE_RESOURCE_GROUP }}" \ + --name "${{ vars.AZURE_VM_NAME }}" + + # 注意:VM 上的預設 shell 不是 bash,所以只用 POSIX 的 set -eu(沒有 pipefail) + # run-command 即使腳本失敗也可能回報成功,所以腳本最後印出 DEPLOY_OK,由這裡驗證。 + - name: Deploy to ${{ inputs.environment }} VM + env: + JAR_URL: ${{ github.server_url }}/${{ github.repository }}/releases/download/${{ env.RELEASE_TAG }}/simpleweb.jar + run: | + output="$(az vm run-command invoke \ + --resource-group "${{ vars.AZURE_RESOURCE_GROUP }}" \ + --name "${{ vars.AZURE_VM_NAME }}" \ + --command-id RunShellScript \ + --scripts " + set -eu + curl -fsSL --retry 3 -o '$APP_DIR/simpleweb.jar.new' '$JAR_URL' + install -o simpleweb -g simpleweb -m 0644 '$APP_DIR/simpleweb.jar.new' '$APP_DIR/simpleweb.jar' + rm -f '$APP_DIR/simpleweb.jar.new' + printf 'APP_ENVIRONMENT=%s\nAPP_BUILD_SHA=%s\nAPP_BUILD_TIME=%s\n' '$APP_ENVIRONMENT' '${{ github.sha }}' \"\$(date -u +%FT%TZ)\" > '$APP_DIR/app.env' + chown simpleweb:simpleweb '$APP_DIR/app.env' + chmod 0644 '$APP_DIR/app.env' + systemctl restart '$SERVICE_NAME' + echo DEPLOY_OK + " \ + --query "value[0].message" -o tsv)" + echo "$output" + if ! printf '%s' "$output" | grep -q 'DEPLOY_OK'; then + echo "VM 上的部署腳本沒有跑完,請看上面的訊息" >&2 + exit 1 + fi + + # 部署完一定要驗證,而且要比對 buildSha, + # 否則「舊版程式還活著」也會回 200,workflow 就會綠燈騙人 + - name: Smoke test + run: | + body='' + for i in $(seq 1 10); do + body="$(curl -fsS "http://${{ vars.VM_PUBLIC_IP }}:${APP_PORT}/api/info" || true)" + if printf '%s' "$body" | grep -q "$GITHUB_SHA"; then + echo "$body" + echo "${APP_ENVIRONMENT} 環境部署成功" + exit 0 + fi + echo "等待應用程式啟動並回報新版本... ($i/10)" && sleep 6 + done + echo "應用程式在時間內沒有回報這次部署的 commit" >&2 + echo "最後一次回應:$body" >&2 + exit 1 + + - name: Write job summary + if: always() + run: | + { + echo "## Deploy (${APP_ENVIRONMENT})" + echo "" + echo "- 目標目錄:\`${APP_DIR}\`" + echo "- systemd unit:\`${SERVICE_NAME}\`" + echo "- 驗證網址:http://${{ vars.VM_PUBLIC_IP }}:${APP_PORT}/api/info" + echo "- 部署 commit:\`${GITHUB_SHA:0:7}\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index b23b728..6e57a38 100644 --- a/.gitignore +++ b/.gitignore @@ -356,4 +356,12 @@ override.tf.json *_override.tf.json .terraformrc terraform.rc -.terraform.lock.hcl \ No newline at end of file +.terraform.lock.hcl + +# Java / Maven (src-java) +target/ +.mvn/wrapper/maven-wrapper.jar +*.iml +.classpath +.project +.settings/ diff --git a/README.md b/README.md index 72dfac0..2737669 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ A demo ASP.NET Core 10.0 web application showcasing modern DevOps practices, clo - [Docker Compose (Optional)](#docker-compose-optional) - [CI/CD Pipelines](#cicd-pipelines) - [GitHub Actions](#github-actions) + - [Java Edition](#java-edition) + - [Java Workflows](#java-workflows) - [Infrastructure as Code](#infrastructure-as-code) - [Terraform](#terraform) - [Bicep](#bicep) @@ -77,6 +79,12 @@ SimpleWeb/ │ ├── SimpleWeb.UnitTest/ # Unit tests │ ├── SimpleWeb.IntegrationTest/ # Integration tests │ └── SimpleWeb.UITest/ # UI automation tests +├── src-java/ # Java edition (Spring Boot 4.1.1 / Java 21) +│ ├── pom.xml # Maven project (builds target/simpleweb.jar) +│ ├── mvnw / mvnw.cmd / .mvn/ # Maven Wrapper +│ ├── Dockerfile # Container definition +│ ├── src/ # Application and test sources +│ └── README.md # Java edition documentation (Traditional Chinese) ├── ci/ # Azure DevOps pipeline definitions │ ├── 01.build.yml # Basic build pipeline │ ├── 01.prwithlimitbranch.yml # PR validation with branch restriction @@ -112,7 +120,9 @@ SimpleWeb/ ├── 08.aks.yml # Deploy to Azure Kubernetes Service ├── 09.terraform.build.yml # Terraform build workflow ├── 09.terraform.release.yml # Terraform release workflow - └── 10.bicep.yml # Bicep deployment workflow + ├── 10.bicep.yml # Bicep deployment workflow + ├── 12.java-build.yml # Java edition build and test + └── 13.java-vm-deploy.yml # Java edition manual VM deployment ``` ## Prerequisites @@ -281,6 +291,36 @@ The project includes comprehensive GitHub Actions workflows (`.github/workflows/ | `09.terraform.release.yml` | Deploy infrastructure with Terraform and deploy app | | `10.bicep.yml` | Deploy Azure infrastructure with Bicep | +## Java Edition + +Alongside the ASP.NET Core application in `src/`, this repository also contains a **Java edition** +of SimpleWeb in [`src-java/`](src-java/) — a Spring Boot 4.1.1 / Java 21 application that exposes +the same kind of environment and build information. Both editions are built and deployed +independently, so the same DevOps practices can be demonstrated on two technology stacks. + +```bash +cd src-java + +# Build, test and package (produces target/simpleweb.jar) +./mvnw -B verify + +# Run locally on http://localhost:8080 +./mvnw spring-boot:run +``` + +Endpoints: `/` (home page), `/api/info` (JSON), `/actuator/health`, `/actuator/info`. + +Full documentation (Traditional Chinese) — local run, tests, Docker, environment variables and the +generic VM deployment layout under `/opt/simpleweb/{test,prod}` — is in +[`src-java/README.md`](src-java/README.md). + +### Java Workflows + +| Workflow | Description | +|----------|-------------| +| `12.java-build.yml` | Build and test the Java edition on pushes touching `src-java/**` | +| `13.java-vm-deploy.yml` | Manual (`workflow_dispatch`) deployment of the Java edition to a Linux VM, targeting the `test` or `production` GitHub Environment | + ## Infrastructure as Code ### Terraform diff --git a/README_zh-TW.md b/README_zh-TW.md index 96c90cb..d3a3de7 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -17,6 +17,7 @@ - [執行測試](#執行測試) - [Docker 支援](#docker-支援) - [CI/CD 管線](#cicd-管線) +- [Java 版本](#java-版本) - [基礎架構即程式碼](#基礎架構即程式碼) - [Kubernetes 部署](#kubernetes-部署) - [貢獻指南](#貢獻指南) @@ -56,6 +57,12 @@ SimpleWeb/ │ ├── SimpleWeb.UnitTest/ # 單元測試 │ ├── SimpleWeb.IntegrationTest/ # 整合測試 │ └── SimpleWeb.UITest/ # UI 自動化測試 +├── src-java/ # Java 版本(Spring Boot 4.1.1 / Java 21) +│ ├── pom.xml # Maven 專案(產出 target/simpleweb.jar) +│ ├── mvnw / mvnw.cmd / .mvn/ # Maven Wrapper +│ ├── Dockerfile # 容器定義 +│ ├── src/ # 應用程式與測試原始碼 +│ └── README.md # Java 版本說明文件 ├── ci/ # Azure DevOps 管線定義 │ ├── 01.build.yml # 基本建置管線 │ ├── 01.prwithlimitbranch.yml # PR 驗證(限制分支) @@ -91,7 +98,9 @@ SimpleWeb/ ├── 08.aks.yml # 部署至 Azure Kubernetes Service ├── 09.terraform.build.yml # Terraform 建置工作流程 ├── 09.terraform.release.yml # Terraform 發布工作流程 - └── 10.bicep.yml # Bicep 部署工作流程 + ├── 10.bicep.yml # Bicep 部署工作流程 + ├── 12.java-build.yml # Java 版本建置與測試 + └── 13.java-vm-deploy.yml # Java 版本手動 VM 部署 ``` ## 環境需求 @@ -260,6 +269,34 @@ docker-compose down | `09.terraform.release.yml` | 使用 Terraform 部署基礎架構並部署應用程式 | | `10.bicep.yml` | 使用 Bicep 部署 Azure 基礎架構 | +## Java 版本 + +除了 `src/` 的 ASP.NET Core 應用程式之外,本儲存庫還包含 SimpleWeb 的 **Java 版本**, +位於 [`src-java/`](src-java/):以 Spring Boot 4.1.1 / Java 21 實作,提供同樣的環境與建置資訊。 +兩個版本各自獨立建置與部署,用來示範同一套 DevOps 實踐如何套用在不同技術堆疊上。 + +```bash +cd src-java + +# 建置、測試並打包(產出 target/simpleweb.jar) +./mvnw -B verify + +# 在 http://localhost:8080 本機執行 +./mvnw spring-boot:run +``` + +端點:`/`(首頁)、`/api/info`(JSON)、`/actuator/health`、`/actuator/info`。 + +完整說明(本機執行、測試、Docker、環境變數,以及 `/opt/simpleweb/{test,prod}` 的通用 VM +部署配置)請見 [`src-java/README.md`](src-java/README.md)。 + +### Java 工作流程 + +| 工作流程 | 說明 | +|----------|-------------| +| `12.java-build.yml` | `src-java/**` 有變更時建置並測試 Java 版本 | +| `13.java-vm-deploy.yml` | 手動(`workflow_dispatch`)部署 Java 版本至 Linux VM,可選擇 `test` 或 `production` GitHub Environment | + ## 基礎架構即程式碼 ### Terraform diff --git a/src-java/.gitattributes b/src-java/.gitattributes new file mode 100644 index 0000000..7e18e66 --- /dev/null +++ b/src-java/.gitattributes @@ -0,0 +1,5 @@ +/mvnw text eol=lf +*.cmd text eol=crlf +*.sh text eol=lf +*.yml text eol=lf +*.yaml text eol=lf diff --git a/src-java/.mvn/wrapper/maven-wrapper.properties b/src-java/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/src-java/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/src-java/Dockerfile b/src-java/Dockerfile new file mode 100644 index 0000000..f52d4c3 --- /dev/null +++ b/src-java/Dockerfile @@ -0,0 +1,24 @@ +# ---- build stage ------------------------------------------------------------- +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /workspace + +# Dependencies first so Docker can cache them between source-only changes. +COPY pom.xml . +RUN mvn -B -e dependency:go-offline + +COPY src ./src +RUN mvn -B package + +# ---- runtime stage ----------------------------------------------------------- +FROM eclipse-temurin:21-jre +WORKDIR /opt/simpleweb + +COPY --from=build /workspace/target/simpleweb.jar ./simpleweb.jar + +ENV SERVER_PORT=8080 \ + APP_ENVIRONMENT=local \ + APP_BUILD_SHA=dev \ + APP_BUILD_TIME=unknown + +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "/opt/simpleweb/simpleweb.jar"] diff --git a/src-java/README.md b/src-java/README.md new file mode 100644 index 0000000..49d9474 --- /dev/null +++ b/src-java/README.md @@ -0,0 +1,188 @@ +# SimpleWeb Java Edition + +SimpleWeb 的 **Java 版本**:以 Spring Boot 4.1.1 / Java 21 實作,與既有的 C# (ASP.NET Core) 版本 +並存於同一個儲存庫。兩個版本各自獨立建置、各自獨立部署,用來示範同一套 DevOps 流程 +(CI、成品發佈、環境保護、VM 部署)如何套用在不同技術堆疊上。 + +> 📁 C# 版本位於 [`src/`](../src/);本文件只描述 `src-java/` 這個 Maven 專案。 + +## 目錄 + +- [專案結構](#專案結構) +- [環境需求](#環境需求) +- [本機執行](#本機執行) +- [執行測試](#執行測試) +- [端點](#端點) +- [環境變數](#環境變數) +- [Docker](#docker) +- [部署到 VM](#部署到-vm) +- [GitHub Actions 工作流程](#github-actions-工作流程) + +## 專案結構 + +``` +src-java/ +├── pom.xml # Maven 專案定義(finalName 固定為 simpleweb) +├── mvnw / mvnw.cmd / .mvn/ # Maven Wrapper,不需要事先安裝 Maven +├── Dockerfile # 多階段建置:maven 建置 + temurin JRE 執行 +└── src/ + ├── main/ + │ ├── java/money/gh200/simpleweb/ + │ │ ├── SimpleWebApplication.java # 進入點 + │ │ ├── model/AppInfo.java # 首頁與 /api/info 共用的資料快照 + │ │ ├── service/InfoService.java # 組出環境、版本、建置資訊 + │ │ └── web/ # HomeController(頁面)、InfoApiController(API) + │ └── resources/ + │ ├── application.yml # 設定(全部可用環境變數覆寫) + │ ├── templates/index.html # Thymeleaf 首頁 + │ └── static/css/site.css # 樣式 + └── test/java/money/gh200/simpleweb/ + ├── SimpleWebApplicationIT.java # 整合測試(Failsafe,*IT 結尾) + ├── service/InfoServiceTest.java # 單元測試(Surefire) + └── web/HomeControllerTest.java # MVC 切片測試 +``` + +建置產出物固定為 **`target/simpleweb.jar`**(由 `pom.xml` 的 `` 決定)。 +部署腳本與工作流程都直接引用這個路徑,改名會讓部署失敗。 + +## 環境需求 + +- [JDK 21](https://adoptium.net/temurin/releases/?version=21)(Temurin 或其他發行版皆可) +- [Docker](https://www.docker.com/get-started)(選用,僅容器化時需要) +- 不需要另外安裝 Maven,專案已內含 Maven Wrapper + +## 本機執行 + +```bash +cd src-java + +# Linux / macOS +./mvnw spring-boot:run + +# Windows +.\mvnw.cmd spring-boot:run +``` + +預設在 啟動。也可以先打包再直接執行 jar: + +```bash +./mvnw -B clean package +java -jar target/simpleweb.jar +``` + +## 執行測試 + +```bash +# 單元測試(Surefire) +./mvnw -B test + +# 單元測試 + 整合測試 + 打包(Failsafe,CI 使用的指令) +./mvnw -B verify +``` + +`verify` 會執行 `*Test` 與 `*IT` 兩類測試,並產生 `target/simpleweb.jar`。 + +## 端點 + +| 端點 | 方法 | 說明 | +|------|------|------| +| `/` | GET | 首頁,依環境顯示不同顏色的橫幅 | +| `/api/info` | GET | 應用程式與建置資訊(JSON) | +| `/actuator/health` | GET | 健康檢查 | +| `/actuator/info` | GET | Actuator 資訊端點 | + +`/api/info` 回應範例: + +```json +{ + "application": "SimpleWeb", + "version": "1.0.0", + "environment": "test", + "buildSha": "a1b2c3d", + "buildTime": "2026-09-03T00:00:00Z", + "hostname": "vm-simpleweb", + "javaVersion": "21.0.11", + "serverTime": "2026-09-03 08:00:00 CST" +} +``` + +## 環境變數 + +| 變數 | 預設值 | 說明 | +|------|--------|------| +| `SERVER_PORT` | `8080` | HTTP 監聽埠 | +| `APP_ENVIRONMENT` | `local` | 只接受 `local`、`test`、`production`;其他值一律退回 `local`,避免誤顯示正式環境橫幅 | +| `APP_BUILD_SHA` | `dev` | 建置來源 commit,由部署流程寫入 | +| `APP_BUILD_TIME` | `unknown` | 建置/部署時間(UTC),由部署流程寫入 | + +## Docker + +```bash +cd src-java + +docker build -t simpleweb-java:latest . + +docker run -d -p 8080:8080 \ + -e APP_ENVIRONMENT=local \ + --name simpleweb-java simpleweb-java:latest +``` + +`Dockerfile` 為多階段建置:第一階段以 `maven:3.9-eclipse-temurin-21` 打包, +第二階段只帶 `eclipse-temurin:21-jre` 與 jar,減少映像體積。 + +## 部署到 VM + +部署採用「一台 Linux VM、兩個 systemd 服務」的通用配置,測試與正式環境彼此隔離: + +| 環境 | 安裝目錄 | systemd unit | 預設埠 | +|------|----------|--------------|--------| +| 測試 | `/opt/simpleweb/test` | `simpleweb-test` | 8080 | +| 正式 | `/opt/simpleweb/prod` | `simpleweb-prod` | 8081 | + +VM 端需事先準備(由管理者一次性完成,不在工作流程內建立): + +1. 建立不可登入的服務帳號 `simpleweb`,以及上述兩個目錄(owner 為 `simpleweb`)。 +2. 安裝 JRE 21。 +3. 為每個環境建立 systemd unit,指向該環境的 jar,並讀取同目錄的 `app.env`: + + ```ini + [Unit] + Description=SimpleWeb (test) + After=network.target + + [Service] + User=simpleweb + EnvironmentFile=/opt/simpleweb/test/app.env + Environment=SERVER_PORT=8080 + ExecStart=/usr/bin/java -jar /opt/simpleweb/test/simpleweb.jar + Restart=on-failure + + [Install] + WantedBy=multi-user.target + ``` + +部署流程(`13.java-vm-deploy.yml`)會把 jar 安裝到對應目錄、寫入 `app.env` +(`APP_ENVIRONMENT` / `APP_BUILD_SHA` / `APP_BUILD_TIME`)、重啟服務,最後輪詢 `/api/info` +並比對 `buildSha` 是否等於這次部署的 commit —— 只看到 HTTP 200 不算部署成功, +因為舊版程式還活著時也會回 200。 + +## GitHub Actions 工作流程 + +| 工作流程 | 觸發方式 | 說明 | +|----------|----------|------| +| [`12.java-build.yml`](../.github/workflows/12.java-build.yml) | 推送且 `src-java/**` 或此工作流程檔有變更、手動 | `./mvnw -B verify`,上傳 `simpleweb.jar` 成品 | +| [`13.java-vm-deploy.yml`](../.github/workflows/13.java-vm-deploy.yml) | **僅手動**(選擇 `test` 或 `production`) | 建置後發佈滾動式 Release asset,透過 OIDC 登入 Azure,以 `az vm run-command` 部署,並以 `buildSha` 驗證;同時間只允許一個部署(concurrency) | + +`13.java-vm-deploy.yml` 需要下列設定(可設在 Repository 或 Environment 層級): + +| 類型 | 名稱 | 說明 | +|------|------|------| +| Variable | `AZURE_RESOURCE_GROUP` | VM 所在的資源群組 | +| Variable | `AZURE_VM_NAME` | 目標 VM 名稱 | +| Variable | `VM_PUBLIC_IP` | 對外 IP,供 smoke test 與環境連結使用 | +| Secret | `AZURE_CLIENT_ID` | 用於 OIDC 的 App Registration client ID | +| Secret | `AZURE_TENANT_ID` | Entra ID 租用戶 ID | +| Secret | `AZURE_SUBSCRIPTION_ID` | 訂閱 ID | + +> 🔒 正式環境的保護(required reviewers、wait timer、可部署分支)請在 +> GitHub Environment `production` 設定,工作流程本身不寫死任何審核邏輯。 diff --git a/src-java/mvnw b/src-java/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/src-java/mvnw @@ -0,0 +1,295 @@ +#!/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.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=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 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/src-java/mvnw.cmd b/src-java/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/src-java/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@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.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/src-java/pom.xml b/src-java/pom.xml new file mode 100644 index 0000000..a1f9f91 --- /dev/null +++ b/src-java/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.1 + + + + money.gh200 + simpleweb + 1.0.0 + simpleweb + GH-200 GitHub Actions training demo web application + + + 21 + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-thymeleaf-test + test + + + org.springframework.boot + spring-boot-starter-actuator-test + test + + + + + + simpleweb + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + diff --git a/src-java/src/main/java/money/gh200/simpleweb/SimpleWebApplication.java b/src-java/src/main/java/money/gh200/simpleweb/SimpleWebApplication.java new file mode 100644 index 0000000..78be1ae --- /dev/null +++ b/src-java/src/main/java/money/gh200/simpleweb/SimpleWebApplication.java @@ -0,0 +1,12 @@ +package money.gh200.simpleweb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SimpleWebApplication { + + public static void main(String[] args) { + SpringApplication.run(SimpleWebApplication.class, args); + } +} diff --git a/src-java/src/main/java/money/gh200/simpleweb/model/AppInfo.java b/src-java/src/main/java/money/gh200/simpleweb/model/AppInfo.java new file mode 100644 index 0000000..4e0d249 --- /dev/null +++ b/src-java/src/main/java/money/gh200/simpleweb/model/AppInfo.java @@ -0,0 +1,15 @@ +package money.gh200.simpleweb.model; + +/** + * Everything the demo page and {@code /api/info} show. One immutable snapshot per request. + */ +public record AppInfo( + String application, + String version, + String environment, + String buildSha, + String buildTime, + String hostname, + String javaVersion, + String serverTime) { +} diff --git a/src-java/src/main/java/money/gh200/simpleweb/service/InfoService.java b/src-java/src/main/java/money/gh200/simpleweb/service/InfoService.java new file mode 100644 index 0000000..09ed11d --- /dev/null +++ b/src-java/src/main/java/money/gh200/simpleweb/service/InfoService.java @@ -0,0 +1,131 @@ +package money.gh200.simpleweb.service; + +import java.net.InetAddress; +import java.time.Clock; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.function.Supplier; + +import money.gh200.simpleweb.model.AppInfo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * Builds the snapshot of "who am I and where am I running" that the demo page + * and the {@code /api/info} endpoint both render. + * + *

The environment and the build metadata are supplied by systemd through + * environment variables, so this is the single place that decides what happens + * when they are missing or oddly formatted. + */ +@Service +public class InfoService { + + public static final String DEFAULT_ENVIRONMENT = "local"; + public static final String DEFAULT_BUILD_SHA = "dev"; + public static final String DEFAULT_BUILD_TIME = "unknown"; + public static final String UNKNOWN_HOSTNAME = "unknown"; + + private static final DateTimeFormatter SERVER_TIME_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z", Locale.ROOT); + + private final String applicationName; + private final String version; + private final String environment; + private final String buildSha; + private final String buildTime; + private final Clock clock; + private final Supplier hostnameSupplier; + + @Autowired + public InfoService( + @Value("${app.name:SimpleWeb}") String applicationName, + @Value("${app.version:unknown}") String version, + @Value("${app.environment:local}") String environment, + @Value("${app.build.sha:dev}") String buildSha, + @Value("${app.build.time:unknown}") String buildTime) { + + this(applicationName, version, environment, buildSha, buildTime, + Clock.systemDefaultZone(), InfoService::resolveSystemHostname); + } + + InfoService(String applicationName, String version, String environment, String buildSha, + String buildTime, Clock clock, Supplier hostnameSupplier) { + + this.applicationName = orDefault(applicationName, "SimpleWeb"); + this.version = orDefault(version, "unknown"); + this.environment = normalizeEnvironment(environment); + this.buildSha = orDefault(buildSha, DEFAULT_BUILD_SHA); + this.buildTime = orDefault(buildTime, DEFAULT_BUILD_TIME); + this.clock = clock; + this.hostnameSupplier = hostnameSupplier; + } + + public AppInfo currentInfo() { + return new AppInfo( + applicationName, + version, + environment, + buildSha, + buildTime, + hostname(), + System.getProperty("java.version"), + serverTime()); + } + + /** CSS class that drives the big colour-coded banner on the home page. */ + public String bannerClass() { + return switch (environment) { + case "test" -> "env-test"; + case "production" -> "env-production"; + default -> "env-local"; + }; + } + + public String environment() { + return environment; + } + + private String serverTime() { + return ZonedDateTime.now(clock).format(SERVER_TIME_FORMAT); + } + + private String hostname() { + try { + return orDefault(hostnameSupplier.get(), UNKNOWN_HOSTNAME); + } catch (RuntimeException ex) { + return UNKNOWN_HOSTNAME; + } + } + + /** + * Unknown or misspelled values fall back to {@code local} so the page never + * shows a production-red banner by accident. + */ + static String normalizeEnvironment(String value) { + String normalized = orDefault(value, DEFAULT_ENVIRONMENT).toLowerCase(Locale.ROOT); + return switch (normalized) { + case "test", "production", "local" -> normalized; + default -> DEFAULT_ENVIRONMENT; + }; + } + + private static String orDefault(String value, String fallback) { + return (value == null || value.isBlank()) ? fallback : value.trim(); + } + + private static String resolveSystemHostname() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (Exception ex) { + String fromEnv = System.getenv("COMPUTERNAME"); + if (fromEnv == null || fromEnv.isBlank()) { + fromEnv = System.getenv("HOSTNAME"); + } + return (fromEnv == null || fromEnv.isBlank()) ? UNKNOWN_HOSTNAME : fromEnv; + } + } +} diff --git a/src-java/src/main/java/money/gh200/simpleweb/web/HomeController.java b/src-java/src/main/java/money/gh200/simpleweb/web/HomeController.java new file mode 100644 index 0000000..adbbf01 --- /dev/null +++ b/src-java/src/main/java/money/gh200/simpleweb/web/HomeController.java @@ -0,0 +1,24 @@ +package money.gh200.simpleweb.web; + +import money.gh200.simpleweb.service.InfoService; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HomeController { + + private final InfoService infoService; + + public HomeController(InfoService infoService) { + this.infoService = infoService; + } + + @GetMapping("/") + public String index(Model model) { + model.addAttribute("info", infoService.currentInfo()); + model.addAttribute("bannerClass", infoService.bannerClass()); + return "index"; + } +} diff --git a/src-java/src/main/java/money/gh200/simpleweb/web/InfoApiController.java b/src-java/src/main/java/money/gh200/simpleweb/web/InfoApiController.java new file mode 100644 index 0000000..ecbec2b --- /dev/null +++ b/src-java/src/main/java/money/gh200/simpleweb/web/InfoApiController.java @@ -0,0 +1,22 @@ +package money.gh200.simpleweb.web; + +import money.gh200.simpleweb.model.AppInfo; +import money.gh200.simpleweb.service.InfoService; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class InfoApiController { + + private final InfoService infoService; + + public InfoApiController(InfoService infoService) { + this.infoService = infoService; + } + + @GetMapping("/api/info") + public AppInfo info() { + return infoService.currentInfo(); + } +} diff --git a/src-java/src/main/resources/application.yml b/src-java/src/main/resources/application.yml new file mode 100644 index 0000000..d0bcb26 --- /dev/null +++ b/src-java/src/main/resources/application.yml @@ -0,0 +1,23 @@ +server: + port: ${SERVER_PORT:8080} + +spring: + application: + name: simpleweb + +app: + name: SimpleWeb + version: @project.version@ + environment: ${APP_ENVIRONMENT:local} + build: + sha: ${APP_BUILD_SHA:dev} + time: ${APP_BUILD_TIME:unknown} + +management: + endpoints: + web: + exposure: + include: health,info + endpoint: + health: + show-details: never diff --git a/src-java/src/main/resources/static/css/site.css b/src-java/src/main/resources/static/css/site.css new file mode 100644 index 0000000..3e8f8ca --- /dev/null +++ b/src-java/src/main/resources/static/css/site.css @@ -0,0 +1,139 @@ +:root { + --ink: #1b1f23; + --muted: #6a737d; + --line: #e1e4e8; + --surface: #ffffff; + --page: #f6f8fa; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--page); + color: var(--ink); + font-family: "Segoe UI", "Noto Sans TC", Roboto, Helvetica, Arial, sans-serif; + line-height: 1.5; +} + +.banner { + padding: 3.5rem 1.5rem; + text-align: center; + color: #ffffff; +} + +.banner-label { + margin: 0; + font-size: 0.95rem; + letter-spacing: 0.4em; + text-transform: uppercase; + opacity: 0.85; +} + +.banner-env { + margin: 0.25rem 0 0.5rem; + font-size: clamp(3rem, 12vw, 7rem); + font-weight: 800; + letter-spacing: 0.08em; + line-height: 1; +} + +.banner-app { + margin: 0; + font-size: 1.25rem; + opacity: 0.9; +} + +.env-test { + background: linear-gradient(135deg, #0b5fff, #0a3fa8); +} + +.env-production { + background: linear-gradient(135deg, #e8590c, #c92a2a); +} + +.env-local { + background: linear-gradient(135deg, #6a737d, #424a53); +} + +.content { + max-width: 62rem; + margin: 0 auto; + padding: 2.5rem 1.5rem 3.5rem; +} + +h2 { + font-size: 1.15rem; + text-transform: uppercase; + letter-spacing: 0.12em; + color: var(--muted); + margin: 2rem 0 1rem; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); + gap: 1rem; +} + +.card { + display: flex; + flex-direction: column; + gap: 0.35rem; + background: var(--surface); + border: 1px solid var(--line); + border-radius: 0.75rem; + padding: 1.1rem 1.25rem; +} + +.card-label { + font-size: 0.8rem; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--muted); +} + +.card-value { + font-size: 1.2rem; + font-weight: 600; + word-break: break-all; +} + +.mono { + font-family: Consolas, "Cascadia Mono", "Courier New", monospace; +} + +.links { + list-style: none; + padding: 0; + margin: 0; + display: grid; + gap: 0.5rem; +} + +.links li { + background: var(--surface); + border: 1px solid var(--line); + border-radius: 0.75rem; + padding: 0.85rem 1.25rem; +} + +.links a { + font-family: Consolas, "Cascadia Mono", "Courier New", monospace; + font-weight: 600; + color: #0b5fff; + text-decoration: none; +} + +.links a:hover { + text-decoration: underline; +} + +.footer { + margin-top: 2.5rem; + text-align: center; + color: var(--muted); + font-size: 0.9rem; +} diff --git a/src-java/src/main/resources/templates/index.html b/src-java/src/main/resources/templates/index.html new file mode 100644 index 0000000..0e8cb2e --- /dev/null +++ b/src-java/src/main/resources/templates/index.html @@ -0,0 +1,57 @@ + + + + + + SimpleWeb + + + + +

+ +
+

Deployment details

+ +
+
+ Build SHA + dev +
+
+ Build time + unknown +
+
+ Hostname + localhost +
+
+ Version + 1.0.0 +
+
+ Server time + - +
+
+ Java version + 21 +
+
+ +

Endpoints

+ + + +
+ + + diff --git a/src-java/src/test/java/money/gh200/simpleweb/SimpleWebApplicationIT.java b/src-java/src/test/java/money/gh200/simpleweb/SimpleWebApplicationIT.java new file mode 100644 index 0000000..c7121b8 --- /dev/null +++ b/src-java/src/test/java/money/gh200/simpleweb/SimpleWebApplicationIT.java @@ -0,0 +1,73 @@ +package money.gh200.simpleweb; + +import java.util.Map; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.RestClient; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Starts the real application on a random port (never a fixed one, so it can run + * on a build agent that is already using 8080) and calls it over HTTP. + */ +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "app.environment=test", + "app.build.sha=deadbee", + "app.build.time=2026-09-03T00:10:00Z" + }) +class SimpleWebApplicationIT { + + @LocalServerPort + private int port; + + private RestClient client() { + return RestClient.create("http://localhost:" + port); + } + + @Test + @DisplayName("/api/info 回傳這次部署的完整資訊") + void infoEndpointReturnsTheDeployedBuildMetadata() { + var response = client().get().uri("/api/info").retrieve() + .toEntity(new ParameterizedTypeReference>() {}); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + Map body = response.getBody(); + assertThat(body).isNotNull(); + assertThat(body).containsEntry("application", "SimpleWeb") + .containsEntry("version", "1.0.0") + .containsEntry("environment", "test") + .containsEntry("buildSha", "deadbee") + .containsEntry("buildTime", "2026-09-03T00:10:00Z"); + assertThat(body.get("hostname")).isNotBlank(); + assertThat(body.get("javaVersion")).startsWith("21"); + assertThat(body.get("serverTime")).isNotBlank(); + } + + @Test + @DisplayName("/ 回傳 HTML 首頁並帶有藍色 test 橫幅") + void homePageIsServedWithTheTestBanner() { + var response = client().get().uri("/").retrieve().toEntity(String.class); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).contains("TEST").contains("env-test").contains("deadbee"); + } + + @Test + @DisplayName("/actuator/health 回報 UP") + void healthEndpointReportsUp() { + var response = client().get().uri("/actuator/health").retrieve() + .toEntity(new ParameterizedTypeReference>() {}); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).containsEntry("status", "UP"); + } +} diff --git a/src-java/src/test/java/money/gh200/simpleweb/service/InfoServiceTest.java b/src-java/src/test/java/money/gh200/simpleweb/service/InfoServiceTest.java new file mode 100644 index 0000000..640b447 --- /dev/null +++ b/src-java/src/test/java/money/gh200/simpleweb/service/InfoServiceTest.java @@ -0,0 +1,87 @@ +package money.gh200.simpleweb.service; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; + +import money.gh200.simpleweb.model.AppInfo; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; + +class InfoServiceTest { + + private static final Clock FIXED_CLOCK = + Clock.fixed(Instant.parse("2026-09-03T01:23:45Z"), ZoneId.of("UTC")); + + private static InfoService serviceWith(String environment, String buildSha, String buildTime) { + return new InfoService("SimpleWeb", "1.0.0", environment, buildSha, buildTime, + FIXED_CLOCK, () -> "gh200-vm"); + } + + @Test + @DisplayName("回傳 CI 注入的建置資訊") + void exposesTheBuildMetadataInjectedByCi() { + AppInfo info = serviceWith("production", "a1b2c3d", "2026-09-03T00:10:00Z").currentInfo(); + + assertThat(info.application()).isEqualTo("SimpleWeb"); + assertThat(info.version()).isEqualTo("1.0.0"); + assertThat(info.environment()).isEqualTo("production"); + assertThat(info.buildSha()).isEqualTo("a1b2c3d"); + assertThat(info.buildTime()).isEqualTo("2026-09-03T00:10:00Z"); + assertThat(info.hostname()).isEqualTo("gh200-vm"); + assertThat(info.javaVersion()).isEqualTo(System.getProperty("java.version")); + assertThat(info.serverTime()).isEqualTo("2026-09-03 01:23:45 UTC"); + } + + @ParameterizedTest(name = "APP_ENVIRONMENT=\"{0}\" -> {1}") + @CsvSource({ + "test, test", + " TEST , test", + "Production, production", + "local, local", + "staging, local", + "'', local" + }) + @DisplayName("環境名稱正規化,未知的值一律當成 local") + void normalizesEnvironmentAndFallsBackToLocal(String rawEnvironment, String expected) { + assertThat(serviceWith(rawEnvironment, "sha", "time").environment()).isEqualTo(expected); + } + + @Test + @DisplayName("環境變數沒設定時使用預設值") + void usesDefaultsWhenEnvironmentVariablesAreMissing() { + AppInfo info = serviceWith(null, null, " ").currentInfo(); + + assertThat(info.environment()).isEqualTo(InfoService.DEFAULT_ENVIRONMENT); + assertThat(info.buildSha()).isEqualTo(InfoService.DEFAULT_BUILD_SHA); + assertThat(info.buildTime()).isEqualTo(InfoService.DEFAULT_BUILD_TIME); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ + "test, env-test", + "production, env-production", + "local, env-local", + "whatever, env-local" + }) + @DisplayName("每個環境對應到自己的橫幅顏色") + void mapsEachEnvironmentToItsOwnBannerColour(String environment, String expectedCssClass) { + assertThat(serviceWith(environment, "sha", "time").bannerClass()).isEqualTo(expectedCssClass); + } + + @Test + @DisplayName("主機名稱查不到時不會讓頁面爆掉") + void survivesAHostnameLookupFailure() { + InfoService service = new InfoService("SimpleWeb", "1.0.0", "test", "sha", "time", + FIXED_CLOCK, () -> { + throw new IllegalStateException("no DNS on this box"); + }); + + assertThat(service.currentInfo().hostname()).isEqualTo(InfoService.UNKNOWN_HOSTNAME); + } +} diff --git a/src-java/src/test/java/money/gh200/simpleweb/web/HomeControllerTest.java b/src-java/src/test/java/money/gh200/simpleweb/web/HomeControllerTest.java new file mode 100644 index 0000000..f78334a --- /dev/null +++ b/src-java/src/test/java/money/gh200/simpleweb/web/HomeControllerTest.java @@ -0,0 +1,42 @@ +package money.gh200.simpleweb.web; + +import money.gh200.simpleweb.service.InfoService; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@WebMvcTest(HomeController.class) +@Import(InfoService.class) +@TestPropertySource(properties = { + "app.environment=test", + "app.build.sha=abc1234", + "app.build.time=2026-09-03T00:10:00Z" +}) +class HomeControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + @DisplayName("首頁回 200 並顯示環境名稱與建置資訊") + void homePageShowsTheEnvironmentAndBuildInformation() throws Exception { + mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(view().name("index")) + .andExpect(content().string(containsString("TEST"))) + .andExpect(content().string(containsString("env-test"))) + .andExpect(content().string(containsString("abc1234"))) + .andExpect(content().string(containsString("2026-09-03T00:10:00Z"))); + } +}