"""Offline Maven first-project archetype, Gson POM, JAR packaging & mirror verifier for Ch04 (start)."""
import json
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Maven POM/lifecycle/dependency verifier (mvn CLI absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = []
# Case 1: Archetype generate parameters & standard 4-dir source tree
cli_args = [
"-DgroupId=com.example",
"-DartifactId=my-first-app",
"-DarchetypeArtifactId=maven-archetype-quickstart",
"-DinteractiveMode=false",
]
parsed = dict(item[2:].split("=", 1) for item in cli_args)
pkg_path = parsed["groupId"].replace(".", "/")
expected_files = [
f"{parsed['artifactId']}/pom.xml",
f"{parsed['artifactId']}/src/main/java/{pkg_path}/App.java",
f"{parsed['artifactId']}/src/test/java/{pkg_path}/AppTest.java",
]
cases.append(
check(
"archetype_generate_params_and_layout",
"Parse archetype:generate -D parameters and verify generated App.java/AppTest.java paths",
{
"groupId": "com.example",
"artifactId": "my-first-app",
"archetype": "maven-archetype-quickstart",
"interactiveMode": "false",
"app_path": "my-first-app/src/main/java/com/example/App.java",
"test_path": "my-first-app/src/test/java/com/example/AppTest.java",
},
{
"groupId": parsed["groupId"],
"artifactId": parsed["artifactId"],
"archetype": parsed["archetypeArtifactId"],
"interactiveMode": parsed["interactiveMode"],
"app_path": expected_files[1],
"test_path": expected_files[2],
},
)
)
# Case 2: POM dependency parsing with added Gson (default compile scope)
pom_xml = """
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-first-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-first-app</name>
<url>http://www.example.com</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
</project>
"""
root = ET.fromstring(pom_xml)
deps = []
for d in root.findall("dependencies/dependency"):
deps.append(
{
"gav": f"{d.findtext('groupId')}:{d.findtext('artifactId')}:{d.findtext('version')}",
"scope": d.findtext("scope") or "compile",
}
)
cases.append(
check(
"pom_xml_and_gson_dependency",
"Parse initial & Gson-extended pom.xml verifying junit(test) and gson(default compile) scopes",
{
"packaging": "jar",
"dependencies": [
{"gav": "junit:junit:4.12", "scope": "test"},
{"gav": "com.google.code.gson:gson:2.8.9", "scope": "compile"},
],
"gson_json_demo": json.dumps("Hello Maven with Gson!"),
},
{
"packaging": root.findtext("packaging"),
"dependencies": deps,
"gson_json_demo": '"Hello Maven with Gson!"',
},
)
)
# Case 3: Build output directories & JAR archive assembly via zipfile
with tempfile.TemporaryDirectory() as tmp:
proj = Path(tmp) / "my-first-app"
classes_dir = proj / "target" / "classes" / "com" / "example"
reports_dir = proj / "target" / "surefire-reports"
classes_dir.mkdir(parents=True)
reports_dir.mkdir(parents=True)
(classes_dir / "App.class").write_bytes(b"\xca\xfe\xba\xbe")
(reports_dir / "com.example.AppTest.txt").write_text("Tests run: 1, Failures: 0\n", encoding="utf-8")
jar_path = proj / "target" / "my-first-app-1.0-SNAPSHOT.jar"
with zipfile.ZipFile(jar_path, "w") as zf:
zf.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\nCreated-By: Offline Verifier\n")
zf.write(classes_dir / "App.class", "com/example/App.class")
with zipfile.ZipFile(jar_path, "r") as zf:
jar_entries = sorted(zf.namelist())
has_reports = (reports_dir / "com.example.AppTest.txt").is_file()
cases.append(
check(
"build_lifecycle_and_jar_packaging",
"Verify target/classes, target/surefire-reports, and packaged my-first-app-1.0-SNAPSHOT.jar entries",
{
"jar_name": "my-first-app-1.0-SNAPSHOT.jar",
"entries": ["META-INF/MANIFEST.MF", "com/example/App.class"],
"surefire_report_present": True,
},
{
"jar_name": jar_path.name,
"entries": jar_entries,
"surefire_report_present": has_reports,
},
)
)
# Case 4: Aliyun mirror XML & compiler source/target properties
mirror_xml = """
<mirror>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
"""
props_xml = """
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
"""
m_root = ET.fromstring(mirror_xml)
pr_root = ET.fromstring(props_xml)
cases.append(
check(
"mirror_and_compiler_version_fix",
"Parse Aliyun mirror configuration and maven.compiler.source/target Java 11 properties",
{
"mirror_id": "aliyun",
"mirror_of": "central",
"compiler_source": "11",
"compiler_target": "11",
},
{
"mirror_id": m_root.findtext("id"),
"mirror_of": m_root.findtext("mirrorOf"),
"compiler_source": pr_root.findtext("maven.compiler.source"),
"compiler_target": pr_root.findtext("maven.compiler.target"),
},
)
)
# Case 5: Core command registry & java -cp vs java -jar distinction
cmd_map = {
"mvn clean": "remove target/",
"mvn compile": "compile src/main/java to target/classes",
"mvn test": "run src/test/java tests",
"mvn package": "package artifact jar/war",
"mvn install": "install artifact into ~/.m2/repository",
}
cases.append(
check(
"java_run_classpath_and_cli_summary",
"Verify 5 foundational Maven commands and java -cp vs executable java -jar requirements",
{
"command_count": 5,
"cp_invocation": "java -cp target/my-first-app-1.0-SNAPSHOT.jar com.example.App",
"jar_flag_requires_manifest_main_class": True,
},
{
"command_count": len(cmd_map),
"cp_invocation": "java -cp target/my-first-app-1.0-SNAPSHOT.jar com.example.App",
"jar_flag_requires_manifest_main_class": True,
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/maven-start-lab/explore-start.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-start.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2175.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2198.zip