<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Joseph Gan's Blog]]></title><description><![CDATA[Joseph Gan's Blog]]></description><link>https://bwgjoseph.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 00:09:29 GMT</lastBuildDate><atom:link href="https://bwgjoseph.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Mastering GitLab Parent‑Child Pipelines: Scalable CI for Multi‑Module Maven Monorepos]]></title><description><![CDATA[Scalable GitLab CI for Maven monorepos. Learn Parent-Child orchestration, ID-based artifact aggregation, and automated DevSecOps security scans.]]></description><link>https://bwgjoseph.com/mastering-gitlab-parent-child-pipelines-scalable-ci-for-multi-module-maven-monorepos</link><guid isPermaLink="true">https://bwgjoseph.com/mastering-gitlab-parent-child-pipelines-scalable-ci-for-multi-module-maven-monorepos</guid><category><![CDATA[GitLab]]></category><category><![CDATA[GitLab-CI]]></category><category><![CDATA[Devops]]></category><category><![CDATA[maven]]></category><category><![CDATA[DevSecOps]]></category><category><![CDATA[automation]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Fri, 05 Jun 2026 18:54:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60e9553dc551f16b0f84748b/9442421f-0e68-437d-a485-3c400031dccb.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Background</h1>
<p>Recently, I redesigned my team's pipeline running on a multi-module Maven monorepo using GitLab CI. It wasn't that the previous setup was broken, but my team faced a few persistent issues that I hoped to resolve to bring the pipeline into a more robust state. I was the one who did the initial setup as well, but that was done when I was still relatively new to GitLab CI. As I worked on this redesign, I learned quite a few lessons along the way that I hope to share with the "future me."</p>
<h1>Objective</h1>
<p>I set out to resolve several key pain points:</p>
<ul>
<li><p><strong>Double Pipelines</strong>: Preventing both branch and MR pipelines from triggering for the same commit.</p>
</li>
<li><p><strong>Artifact Management</strong>: Resolving issues where build artifacts weren't reliably uploaded or shared.</p>
</li>
<li><p><strong>Visibility</strong>: Fixing cases where test coverage (JaCoCo) wasn't being correctly captured.</p>
</li>
</ul>
<p>Beyond just fixing issues, I also wanted to implement several strategic improvements:</p>
<ul>
<li><p><strong>Scalability</strong>: Creating a more robust setup using <code>!reference</code> tags and reusable job templates.</p>
</li>
<li><p><strong>Security</strong>: Integrating automated SAST scans.</p>
</li>
<li><p><strong>Performance</strong>: Reducing overall pipeline runtime through optimized cache strategies and surgical artifact sharing.</p>
</li>
</ul>
<p>Read on to see the architectural patterns and specific pipeline designs that resolved these pain points and enabled us to scale effectively.</p>
<h1>Pipeline design</h1>
<h2>Project Structure</h2>
<p>This is a sample setup, but quite similar to one that I do have. In the actual setup, there's around 10 - 12 modules.</p>
<pre><code class="language-plaintext">. (Root Aggregator)
├── .gitlab-ci.yml           # Root Orchestrator
├── .gitlab-ci-base.yml      # Central CI Blueprint
├── pom.xml                  # Root Aggregator POM
├── parent-pom/              # Shared configuration &amp; dependency management
│   └── pom.xml
└── project/                 # Functional module aggregator
    ├── pom.xml
    ├── mmm-security/        # Foundation module
    │   ├── .gitlab-ci.yml   # Child Pipeline
    │   └── pom.xml
    ├── mmm-core/            # Core application module
    │   ├── .gitlab-ci.yml   # Child Pipeline
    │   └── pom.xml
    ├── mmm-search/          # Search module
    │   ├── .gitlab-ci.yml   # Child Pipeline
    │   └── pom.xml
    └── mmm-report/          # Coverage reporter
        └── pom.xml
</code></pre>
<h2>Pipeline setup</h2>
<p>Configure a parent-child pipeline with the following setup</p>
<ul>
<li><p>Root Orchestrator (<code>.gitlab-ci.yml</code>)</p>
</li>
<li><p>Central Blueprint (<code>.gitlab-ci-base.yml</code>)</p>
</li>
<li><p>Independent Child Pipelines (<code>.gitlab-ci.yml</code> housed within each module)</p>
</li>
</ul>
<h3>Overview</h3>
<img src="https://cdn.hashnode.com/uploads/covers/60e9553dc551f16b0f84748b/911bb00a-a2d6-4010-811d-36b3b0053f4e.svg" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Hands-On: The Interactive CI/CD Playbook</h3>
<p>If you'd like to explore this architecture in a more visual and hands-on way, I've built an <a href="https://bwgjoseph.github.io/tutorials/mastering-gitlab-ci/"><strong>Interactive CI/CD Playbook</strong></a>. It allows you to dive into the project structure, explore how we manage artifact sharing across parent-child pipelines, and see the code snippets in action.</p>
<p><a href="https://bwgjoseph.github.io/tutorials/mastering-gitlab-ci/"><strong>Explore the Playbook →</strong></a></p>
<p>If you prefer to dig into the implementation details and the "why" behind these design decisions, read on—the following best practices break down the architecture component by component.</p>
<hr />
<h1>Best Practices</h1>
<h2>Root Orchestrator</h2>
<p>This is the main controller that defines the <code>workflow</code> rules, the stages available, and when to trigger the downstream child pipelines.</p>
<pre><code class="language-yaml">workflow:
  rules:
    - if: $CI_FULL_PIPELINE == "true"                  # Manual override
    - if: $CI_PIPELINE_SOURCE == "parent_pipeline"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: \(CI_COMMIT_BRANCH &amp;&amp; \)CI_OPEN_MERGE_REQUESTS # Double-pipeline suppression
      when: never
    - if: $CI_COMMIT_BRANCH                             # All branch pushes (including main)
</code></pre>
<ul>
<li><p><code>CI_FULL_PIPELINE</code> allows me to manually trigger full pipeline run</p>
</li>
<li><p><code>CI_COMMIT_BRANCH &amp;&amp; CI_OPEN_MERGE_REQUESTS</code> prevents <strong>Double Pipelines</strong>: a common issue where GitLab triggers both a branch pipeline and an MR pipeline for the same commit.</p>
</li>
</ul>
<pre><code class="language-yaml">stages:
  - configuration
  - foundation
  - application
  - test # setup to run Gitlab built-in SAST scans
  - report

pre:
  stage: .pre
  script:
    - env
</code></pre>
<p><code>.pre</code> is a built-in default stage that always run first. This is useful to see what are all the available environment variables available to the job for ease of troubleshooting.</p>
<blockquote>
<p>While <code>env</code> is great for debugging, it should be used with caution (or removed before production) to avoid accidentally logging environment metadata, even though GitLab masks secrets by default.</p>
</blockquote>
<pre><code class="language-yaml">.trigger-rules:
  rules:
    - if: "$CI_FULL_PIPELINE == 'true'"
      when: always
    # Merge Request: Accuracy check using compare_to
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        compare_to: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
        paths:
          - $MODULE_PATH/**/*
          - parent-pom/**/*
    # Main Branch: Standard change detection
    - if: \(CI_COMMIT_BRANCH == \)CI_DEFAULT_BRANCH &amp;&amp; $CI_COMMIT_BEFORE_SHA != "0000000000000000000000000000000000000000"
      changes:
        - $MODULE_PATH/**/*
        - parent-pom/**/*

trigger-core:
  stage: application
  extends: .trigger-rules
  needs:
    - job: trigger-security
      optional: true
    - job: deploy-parent-pom
      optional: true
  variables:
    MODULE_PATH: "project/mmm-core"
    PARENT_SOURCE: $CI_PIPELINE_SOURCE
    PARENT_BRANCH: $CI_COMMIT_BRANCH
  trigger:
    include: project/mmm-core/.gitlab-ci.yml
    strategy: mirror
</code></pre>
<ul>
<li><p><code>.trigger-rules</code>: Define reusable rules to determine when the job should be triggered. I used <code>compare_to: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME</code> to ensure change detection is calculated accurately against the target branch—eliminating the "rebase noise" that often plagues monorepo pipelines.</p>
</li>
<li><p><code>extends: .trigger-rules</code>: By extending this template, it inherits the centralized change-detection logic. This ensures that only file changes under a specific module (or the parent-pom) trigger a pipeline run—preventing unnecessary resource waste.</p>
</li>
<li><p><code>needs</code>: These are upstream jobs that this job depends on, and if there are changes to those modules, then this job has to wait until those are done before it can run. Having the <code>optional: true</code> is the secret sauce for monorepos: it prevents the pipeline from failing if an upstream module wasn't triggered due to lack of changes.</p>
</li>
<li><p><code>variables</code>: This is especially important in parent-child pipelines as this allows us to pass context to the child pipeline in order to evaluate the rules correctly. When the child pipeline runs, the value for <code>$CI_PIPELINE_SOURCE</code> could be different from when it is run in the parent pipeline.</p>
</li>
<li><p><code>trigger:mirror</code>: Ensures the parent pipeline reflects the downstream (child pipeline) status accurately. See <a href="https://docs.gitlab.com/ci/yaml/#triggerstrategy">docs</a> for more detailed explanation.</p>
</li>
</ul>
<p>This parent-child isolation means a failure in the "Search" module doesn't block the "Core" module's deployment—significantly reducing the "blast radius" of failures in a large monorepo.</p>
<h2>Central Blueprint</h2>
<p>This is where all the global variables, job-templates, stages, cache strategy, and reusable snippets are declared.</p>
<h3>Parameterized Templates (<code>spec:inputs</code>)</h3>
<p>I treated our CI templates like "functions" with a defined interface using <code>spec:inputs</code>. This allows the Root Orchestrator to pass specific configurations (like forcing a full pipeline) without relying on fragile global variables.</p>
<pre><code class="language-yaml"># In .gitlab-ci-base.yml
spec:
  inputs:
    full_pipeline:
      default: "false"

# Usage in .gitlab-ci.yml
include:
  - local: '.gitlab-ci-base.yml'
    inputs:
      full_pipeline: $CI_FULL_PIPELINE
</code></pre>
<h3>Cache Strategy</h3>
<pre><code class="language-yaml">cache: 
  key: "maven-$CI_COMMIT_REF_SLUG"
  paths:
    - .m2/repository/
  policy: pull-push
</code></pre>
<p>Using <code>$CI_COMMIT_REF_SLUG</code> is a standard strategy to define a shared branch-level cache, allowing modules to share internal dependencies. This ensures that once the first job has pulled the necessary dependencies, they are cached locally on the runner (or remotely, like in Minio in my setup). Subsequent jobs or pipelines in the same branch will reuse this cache to prevent redundant downloads, saving bandwidth, preventing race conditions, and shaving time off every run.</p>
<pre><code class="language-yaml">.deploy-snapshot-template:
  extends: .base-maven-job
  stage: release
  interruptible: false # Ensure deployment finishes once started
  cache:
    key: "maven-$CI_COMMIT_REF_SLUG"
    paths:
      - .m2/repository/
    policy: pull
  rules:
    - if: \(CI_COMMIT_BRANCH == \)CI_DEFAULT_BRANCH
  script:
    - |
      echo "Deploying SNAPSHOT for $MODULE_PATH to GitLab Maven Registry..."
      mvn \(MAVEN_CLI_OPTS deploy -pl \)MODULE_PATH -am -DskipTests
</code></pre>
<p>It is important to know when to override the cache policy so that it will not unnecessarily push the updated <code>.m2/repository</code> back to the remote cache if I am sure this job only uses the dependencies to do its job.</p>
<h3>!reference tag</h3>
<pre><code class="language-yaml">.coverage-parser:
  script:
    - |
      echo "Extracting coverage percentage for GitLab UI..."
      REPORT_PATH=\({JACOCO_XML_PATH:-"\)MODULE_PATH/target/site/jacoco/jacoco.xml"}
      echo "DEBUG: Parsing JaCoCo report at: $REPORT_PATH"
      
      if [ -f "$REPORT_PATH" ]; then
        # Use grep -o to extract ONLY the matching tag, then tail -1 to get the aggregate
        # This works correctly even if the entire XML is on a single line.
        LINE_COUNTER=\((grep -o '&lt;counter type="LINE"[^&gt;]*/&gt;' "\)REPORT_PATH" | tail -1 || true)

        if [ -n "$LINE_COUNTER" ]; then
          MISSED=\((echo "\)LINE_COUNTER" | sed -n 's/.*missed="\([0-9]*\)".*/\1/p')
          COVERED=\((echo "\)LINE_COUNTER" | sed -n 's/.*covered="\([0-9]*\)".*/\1/p')
          TOTAL=$((MISSED + COVERED))

          echo "DEBUG: Found LINE counter: missed=\(MISSED, covered=\)COVERED, total=$TOTAL"

          if [ "$TOTAL" -gt 0 ]; then
            PERCENT=\((awk -v c="\)COVERED" -v t="$TOTAL" 'BEGIN {printf "%.2f", (c / t) * 100}')
            echo "Coverage: $PERCENT%"
          else
            echo "Coverage: 0.00%"
          fi
        else
          echo "DEBUG: No LINE counter line found in $REPORT_PATH"
        fi
      fi

# Template for application modules
.application-template:
  extends: .base-maven-job
  stage: build
  variables:
    JACOCO_XML_PATH: "$MODULE_PATH/target/site/jacoco/jacoco.xml"
  script:
    - mvn \(MAVEN_CLI_OPTS verify -pl \)MODULE_PATH -am
    - !reference [.coverage-parser, script]
</code></pre>
<p>This is similar to YAML Anchors, which allows you to reuse snippets across jobs. While that is the case, I find <code>!reference</code> more developer-friendly, as it allows you to select specific keys (like <code>script</code>) to reuse.</p>
<p>Note that YAML Anchors are a native YAML feature and work outside of GitLab, while the <code>!reference</code> tag is a GitLab-specific feature.</p>
<h3>Variables</h3>
<pre><code class="language-yaml">variables:
  # Performance: Use a project-relative path for caching
  MAVEN_REPO_LOCAL: ".m2/repository"
  SONAR_USER_HOME: ".sonar"  # Defines the location of the analysis task cache
  
  # JVM Tuning for CI (Merged with user preferences)
  MAVEN_OPTS: &gt;-
    -Dhttps.protocols=TLSv1.2
    -Dorg.slf4j.simpleLogger.showDateTime=true
    -Djava.awt.headless=true
    -Dfile.encoding=UTF-8
    -Xmx2048m
    -XX:+TieredCompilation
    -XX:TieredStopAtLevel=1

  # Maven CLI optimization (Merged with user preferences)
  MAVEN_CLI_OPTS: &gt;-
    --batch-mode
    --errors
    --fail-at-end
    --show-version
    --no-transfer-progress
    --threads 1C
    -DinstallAtEnd=true
    -DdeployAtEnd=true
    -s .mvn/settings-ci.xml

  GIT_DEPTH: "0"  # Tells git to fetch all the branches of the project, required by the analysis task

  # GitLab FastZip and Compression
  FF_USE_FASTZIP: "true"
  ARTIFACT_COMPRESSION_LEVEL: "fast"
  CACHE_COMPRESSION_LEVEL: "fast"
</code></pre>
<p>I want to draw attention to <code>MAVEN_CLI_OPTS</code> where <code>-s .mvn/settings-ci.xml</code> is defined. This is the unsung hero of our pipeline: it maps <code>${env.CI_JOB_TOKEN}</code> to our GitLab Maven repository, allowing seamless, credential-free publishing and dependency resolution within the CI environment.</p>
<p>I also enabled <code>FF_USE_FASTZIP</code> and <code>fast</code> compression. In a monorepo with 10+ modules, the time saved zipping and unzipping artifacts and cache across dozens of jobs adds up to several minutes per pipeline.</p>
<h3>Artifacts</h3>
<pre><code class="language-yaml">.application-template:
  extends: .base-maven-job
  stage: build
  script:
    - mvn \(MAVEN_CLI_OPTS verify -pl \)MODULE_PATH -am
  artifacts:
    when: always
    paths:
      - "$MODULE_PATH/target/"
    exclude:
      - "$MODULE_PATH/target/*.jar"
    reports:
      junit:
        - "$MODULE_PATH/target/surefire-reports/TEST-*.xml"
        - "$MODULE_PATH/target/failsafe-reports/TEST-*.xml"
      coverage_report:
        coverage_format: jacoco
        path: "$MODULE_PATH/target/site/jacoco/jacoco.xml"
    expire_in: 1 hour
  coverage: '/Coverage: (\d+(?:\.\d+)?)%/'
</code></pre>
<ul>
<li><p><code>when</code>: Set to <code>always</code> so that artifacts are uploaded even on failure, allowing debugging via HTML reports.</p>
</li>
<li><p><code>paths, exclude</code>: Target specific files for upload. Since fat-jar files can be massive, excluding them prevents <code>413 Request Entity Too Large</code> errors.</p>
</li>
<li><p><code>reports</code>: Ensures all relevant reports are submitted to provide coverage data in the GitLab Pipeline UI and the MR widget.</p>
</li>
</ul>
<p>Sharing artifacts across jobs ensures that build products (like <code>/classes</code>) can be reused in subsequent steps, such as <code>jib:build</code>. This significantly reduces container build times by skipping redundant source code re-compilation.</p>
<h3>Sharing artifacts across parent-child Pipeline</h3>
<p>One of the biggest hurdles in Parent-Child pipelines is that <strong>child pipelines run in isolated workspaces.</strong> Standard <code>needs: artifacts: true</code> cannot pull files from a triggered child pipeline back into the root orchestrator.</p>
<p>To solve this for our aggregated reports, I implemented an <strong>ID-based API Collection pattern</strong>:</p>
<ol>
<li><p><strong>Bridge API</strong>: Query the parent pipeline's bridges to find the <code>downstream_pipeline.id</code>.</p>
</li>
<li><p><strong>Jobs API</strong>: Query that child pipeline to find the specific <code>build</code> job ID.</p>
</li>
<li><p><strong>Artifact Download</strong>: Use a <strong>Project Access Token</strong> to download the artifact zip directly via the API.</p>
</li>
</ol>
<p><strong>Why a Project Access Token (PAT)?</strong> Because GitLab's standard <code>$CI_JOB_TOKEN</code> is restricted for security and often cannot cross the pipeline boundary. A PAT with <code>read_api</code> scope ensures our aggregator has the necessary authority.</p>
<pre><code class="language-bash"># Simplified aggregation logic in root orchestrator
for module in mmm-core mmm-search; do
  # 1. Resolve Child Pipeline ID
  CHILD_PIPELINE_ID=\((curl --silent --header "PRIVATE-TOKEN: \){PAT_TOKEN}" \
    "\({CI_API_V4_URL}/projects/\){CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}/bridges" \
    | jq -r ".[] | select(.name==\"trigger-${module#mmm-}\") | .downstream_pipeline.id")

  # 2. Resolve specific Job ID
  CHILD_JOB_ID=\((curl --silent --header "PRIVATE-TOKEN: \){PAT_TOKEN}" \
    "\({CI_API_V4_URL}/projects/\){CHILD_PIPELINE_ID}/jobs" \
    | jq -r ".[] | select(.name==\"build-${module#mmm-}\") | .id")

  # 3. Securely Download
  curl --location --header "PRIVATE-TOKEN: ${PAT_TOKEN}" \
    "\({CI_API_V4_URL}/projects/\){CI_PROJECT_ID}/jobs/${CHILD_JOB_ID}/artifacts" \
    --output "${module}.zip"
done
</code></pre>
<h2>Independent Child Pipelines</h2>
<p>With <code>.gitlab-ci-base.yml</code> providing the blueprint for all child modules, the child pipelines are simple to set up and configure.</p>
<pre><code class="language-yaml"># project/mmm-core/.gitlab-ci.yml
include:
  - local: '.gitlab-ci-base.yml'

variables:
  MODULE_PATH: "project/mmm-core"

build-core:
  extends: .application-template

deploy-core-snapshot:
  extends: .deploy-snapshot-template
  needs: ["build-core"]

deploy-core-image:
  extends: .deploy-image-template
  needs: ["build-core"]

deploy-manifests-prod:
  extends: .deploy-cluster-template
  needs: ["deploy-core-image"]
  resource_group: core-deploy-prod
  environment:
    name: prod
  variables:
    OVERLAY_PATH: "project/mmm-core/k8s/overlays/prod"
    DEPLOYMENT_NAME: "mmm-core"
</code></pre>
<h3>Deployment Safety (<code>resource_group</code>)</h3>
<p>In a monorepo, multiple modules often deploy to the same namespace. If two pipelines trigger simultaneously, they might both try to run <code>kubectl apply</code> for the same module, leading to race conditions.</p>
<p>To prevent this, I implemented module-specific <strong>Resource Groups</strong> as a CI-level mutex:</p>
<pre><code class="language-yaml">deploy-manifests-prod:
  extends: .deploy-cluster-template
  resource_group: core-deploy-prod
  environment:
    name: prod
</code></pre>
<p>By using the naming convention <code>[module]-deploy-[env]</code>:</p>
<ul>
<li><p><strong>Serialization</strong>: Only one pipeline can deploy <code>mmm-core</code> to <code>prod</code> at a time.</p>
</li>
<li><p><strong>Concurrency</strong>: <code>mmm-core</code> and <code>mmm-search</code> can still deploy to <code>prod</code> simultaneously because they use different locks.</p>
</li>
</ul>
<h3>Deployment Rollbacks (The Panic Button)</h3>
<p>No matter how robust your pipeline is, things can still go wrong. To provide a safety net, I paired every deployment job with a manual <strong>Rollback</strong> job.</p>
<pre><code class="language-yaml">rollback-prod:
  extends: .rollback-template
  needs: ["deploy-manifests-prod"]
  resource_group: core-deploy-prod
  variables:
    DEPLOYMENT_NAME: "mmm-core"
    K8S_NAMESPACE: "prod"
</code></pre>
<p>Using <code>kubectl rollout undo</code>, this job allows any team member to immediately revert a failed deployment to its previous stable revision with a single click in the GitLab UI. This "Panic Button" is essential for maintaining high availability in a fast-moving monorepo.</p>
<h1><strong>Shift Left Security</strong></h1>
<p>GitLab provides comprehensive built-in security scanning templates that you can adopt quickly and easily.</p>
<blockquote>
<p>Shift left security means building security testing, compliance checks, and secure coding practices into the earliest phases of the software development life cycle (SDLC).</p>
<p>Source: <a href="https://about.gitlab.com/topics/devsecops/shift-left-security/">https://about.gitlab.com/topics/devsecops/shift-left-security/</a></p>
</blockquote>
<pre><code class="language-yaml"># .gitlab-ci.yml
include:
  - local: '.gitlab-ci-base.yml'
  - template: Jobs/SAST.gitlab-ci.yml
  - template: Jobs/Secret-Detection.gitlab-ci.yml
  - template: Security/Dependency-Scanning.gitlab-ci.yml

stages:
  - ...
  - test # setup to run GitLab built-in scans
  - report
</code></pre>
<p>That's it! You could override the individual job if you want to, but it's optional and some could be overwritten using global variable.</p>
<pre><code class="language-xml">&lt;properties&gt;
	&lt;sonar.version&gt;5.5.0.6356&lt;/sonar.version&gt;
	&lt;sonar.projectKey&gt;bwgjoseph:${project.artifactId}&lt;/sonar.projectKey&gt;
	&lt;sonar.projectName&gt;bwgjoseph:${project.artifactId}&lt;/sonar.projectName&gt;
	&lt;!-- Not necessary for self-hosted --&gt;
	&lt;sonar.organization&gt;bwgjoseph&lt;/sonar.organization&gt;
	&lt;sonar.coverage.jacoco.xmlReportPaths&gt;${project.build.directory}/site/jacoco/jacoco.xml&lt;/sonar.coverage.jacoco.xmlReportPaths&gt;

	&lt;!-- SonarQube Scanner Properties --&gt;
	&lt;sonar.scanner.skipSystemTruststore&gt;true&lt;/sonar.scanner.skipSystemTruststore&gt;
	&lt;sonar.scanner.skipJreProvisioning&gt;true&lt;/sonar.scanner.skipJreProvisioning&gt;
	&lt;!-- Java 25 support: Allow Sonar plugins (like IaC) to access restricted native methods --&gt;
	&lt;sonar.scanner.javaOpts&gt;--enable-native-access=ALL-UNNAMED&lt;/sonar.scanner.javaOpts&gt;
	&lt;!-- Use CI project dir for scanner home if available, fallback to local .sonar --&gt;
	&lt;sonar.userHome&gt;${env.CI_PROJECT_DIR}/.sonar&lt;/sonar.userHome&gt;
&lt;/properties&gt;
</code></pre>
<p>To ensure independent Quality Gates in SonarQube, I enforced unique <code>sonar.projectKey</code> values for each module (e.g., <code>bwgjoseph:${project.artifactId}</code>). Without this, every module analysis would overwrite the previous one in the Sonar dashboard!</p>
<h1><strong>The Extras - Expert Mode</strong></h1>
<p>To take a pipeline from "Functional" to "Enterprise-Ready," I added these high-impact features:</p>
<ul>
<li><p><strong>The Engineering Portal</strong>: I used GitLab Pages to host a unified site for aggregated JaCoCo coverage at <code>/coverage</code> and Maven Documentation at <code>/site</code>. I added a "Gateway Index" in CI that dynamically builds a landing page to navigate between them.</p>
</li>
<li><p><strong>Human-Friendly Triggers</strong>: I leveraged GitLab's <code>variables:options</code> to create a <strong>dropdown menu</strong> in the UI. Now, anyone on the team can manually trigger a full build without needing to remember CLI flags.</p>
</li>
<li><p><strong>The Ghost Aggregator</strong>: I introduced a "code-free" module (<code>mmm-report</code>) purely for aggregation. It provides a clean target for our ID-based artifact collection and prevents our functional modules from being cluttered with aggregation logic.</p>
</li>
<li><p><strong>Inner-Loop Development</strong>: Validate your complex parent-child YAMLs locally using <a href="https://github.com/firecow/gitlab-ci-local">gitlab-ci-local</a>. This shaves hours off the debugging cycle by allowing you to run jobs directly on your machine.</p>
</li>
</ul>
<h1>Conclusion</h1>
<p>At the end of the day, a CI/CD pipeline is only as good as the developer experience it provides. In this redesign, our goal was to make the monorepo feel "small" again—ensuring that a developer working on a single module isn't burdened by the weight of the entire project.</p>
<p>By automating the complex bits—like ID-based artifact collection and cross-pipeline reporting—and providing human-friendly tools like UI-driven triggers and local validation, I’ve built a system that stays out of the way while providing a safety net of "Shift Left" security.</p>
<p>Scaling a monorepo parent-child pipeline isn't just about build commands; it's about orchestration, visibility, and developer experience. Hopefully, these patterns help you (and the future me!) build better pipelines.</p>
<h1><strong>Source Code</strong></h1>
<p>As usual, the full source code is available on <a href="https://github.com/bwgjoseph/tutorials/tree/main/mastering-gitlab-ci"><strong>GitHub</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Spring Security's SecurityContext get unexpectedly cleared in a MockMvc Test]]></title><description><![CDATA[At work, there’s some test written where I wanted to query the database (repository) after mockMvc request has been made to verify the result. This is a…]]></description><link>https://bwgjoseph.com/spring-securitys-securitycontext-get-unexpectedly-cleared-in-a-mockmvc-test</link><guid isPermaLink="true">https://bwgjoseph.com/spring-securitys-securitycontext-get-unexpectedly-cleared-in-a-mockmvc-test</guid><category><![CDATA[spring security]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Java]]></category><category><![CDATA[Spring framework]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 14 Jun 2025 07:42:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749886812351/e8a7109c-c695-460e-95d7-09048f88e1dd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-background">Background</h1>
<p>At work, there’s some test written where I wanted to query the database (repository) after <code>mockMvc</code> request has been made to verify the result. This is a very simple illustration of what it looks like.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootTest</span>
<span class="hljs-meta">@AutoConfigureMockMvc</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeTests</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MockMvc mockMvc;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserRepository repository;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-meta">@WithMockUser(value = "bwgjoseph")</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">this</span>.mockMvc.perform(post(<span class="hljs-string">"/api/v1/users/{name}"</span>, <span class="hljs-string">"bwgjoseph"</span>)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());

        <span class="hljs-comment">// extract data from repository</span>
        <span class="hljs-keyword">var</span> user = <span class="hljs-keyword">this</span>.repository.findByName();

        <span class="hljs-comment">// verify result</span>
        assertThat(user.get()).extracting(<span class="hljs-string">"name"</span>).isEqualTo(<span class="hljs-string">"bwgjoseph"</span>);
    }
}
</code></pre>
<blockquote>
<p>Please note that for simplicity, I have configured my Spring Security <code>user.name</code> as <code>bwgjoseph</code>. And that is why the code above for <code>@WithMockUser</code> is also defined as such. This is to facilitate the <code>@Query</code> used in <code>UserRepository</code> to extract the correct username via the <code>principal?.username</code>.</p>
</blockquote>
<p>Once run, the following exception will be thrown <code>java.lang.IllegalArgumentException: Authentication object cannot be null</code>.</p>
<pre><code class="lang-verilog">org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.expression</span><span class="hljs-variable">.spel</span><span class="hljs-variable">.SpelEvaluationException</span>: EL1021E: A problem occurred whilst attempting to access the <span class="hljs-keyword">property</span> 'principal': 'EL1022E: The <span class="hljs-keyword">function</span> 'principal' mapped to an object of <span class="hljs-keyword">type</span> '<span class="hljs-keyword">class</span> org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.security</span><span class="hljs-variable">.access</span><span class="hljs-variable">.expression</span><span class="hljs-variable">.SecurityExpressionRoot</span>' cannot be invoked'
&lt;omitted&gt;
Caused by: java<span class="hljs-variable">.lang</span><span class="hljs-variable">.IllegalArgumentException</span>: Authentication object cannot be <span class="hljs-literal">null</span>
    at org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.util</span><span class="hljs-variable">.Assert</span><span class="hljs-variable">.notNull</span>(Assert<span class="hljs-variable">.java</span>:<span class="hljs-number">181</span>)
    at org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.security</span><span class="hljs-variable">.access</span><span class="hljs-variable">.expression</span><span class="hljs-variable">.SecurityExpressionRoot</span><span class="hljs-variable">.lambda</span>$new$<span class="hljs-number">1</span>(SecurityExpressionRoot<span class="hljs-variable">.java</span>:<span class="hljs-number">92</span>)
    at org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.util</span><span class="hljs-variable">.function</span><span class="hljs-variable">.SingletonSupplier</span><span class="hljs-variable">.get</span>(SingletonSupplier<span class="hljs-variable">.java</span>:<span class="hljs-number">106</span>)
    at org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.security</span><span class="hljs-variable">.access</span><span class="hljs-variable">.expression</span><span class="hljs-variable">.SecurityExpressionRoot</span><span class="hljs-variable">.getAuthentication</span>(SecurityExpressionRoot<span class="hljs-variable">.java</span>:<span class="hljs-number">130</span>)
    at org<span class="hljs-variable">.springframework</span><span class="hljs-variable">.security</span><span class="hljs-variable">.access</span><span class="hljs-variable">.expression</span><span class="hljs-variable">.SecurityExpressionRoot</span><span class="hljs-variable">.getPrincipal</span>(SecurityExpressionRoot<span class="hljs-variable">.java</span>:<span class="hljs-number">170</span>)
    at java<span class="hljs-variable">.base</span>/jdk<span class="hljs-variable">.internal</span><span class="hljs-variable">.reflect</span><span class="hljs-variable">.DirectMethodHandleAccessor</span><span class="hljs-variable">.invoke</span>(DirectMethodHandleAccessor<span class="hljs-variable">.java</span>:<span class="hljs-number">103</span>)
    ... <span class="hljs-number">44</span> more
</code></pre>
<p>After some digging, I found out that the reason was because <code>SecurityContext</code> is cleared at the end of the filter chain after the <code>mockMvc</code> request, hence, if we were to perform any method call to the repository layer which requires <code>principal (Authentication)</code> object, it will fail.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CrudRepository</span>&lt;<span class="hljs-title">User</span>, <span class="hljs-title">String</span>&gt; </span>{
    <span class="hljs-meta">@Query("SELECT * FROM \"USER\" WHERE name = :#{ principal?.username }")</span>
    <span class="hljs-function">Optional&lt;User&gt; <span class="hljs-title">findByName</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>To fix this, we simply just need to export the <code>SecurityContext</code> for use after the <code>mockMvc</code> request</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.springframework.security.test.web.servlet.response.SecurityMockMvcResultHandlers.exportTestSecurityContext;

<span class="hljs-meta">@Test</span>
<span class="hljs-meta">@WithMockUser(value = "bwgjoseph")</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">this</span>.mockMvc.perform(post(<span class="hljs-string">"/api/v1/users/{name}"</span>, <span class="hljs-string">"bwgjoseph"</span>)
                    .accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_JSON))
            .andDo(exportTestSecurityContext()) <span class="hljs-comment">// to export security context</span>
            .andExpect(status().isCreated());

    <span class="hljs-keyword">var</span> user = <span class="hljs-keyword">this</span>.repository.findByName();

    assertThat(user.get()).extracting(<span class="hljs-string">"name"</span>).isEqualTo(<span class="hljs-string">"bwgjoseph"</span>);
}
</code></pre>
<p>Note that one could manually export the context, but I can’t think of any reason why one would want to do it this way.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-meta">@WithMockUser(value = "bwgjoseph")</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">this</span>.mockMvc.perform(post(<span class="hljs-string">"/api/v1/users/{name}"</span>, <span class="hljs-string">"bwgjoseph"</span>)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .andExpect(status().isOk());

    SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());

    <span class="hljs-keyword">var</span> user = <span class="hljs-keyword">this</span>.repository.findByName();

    assertThat(user.get()).extracting(<span class="hljs-string">"name"</span>).isEqualTo(<span class="hljs-string">"bwgjoseph"</span>);
}
</code></pre>
<h1 id="heading-tips">Tips</h1>
<p>If you encounter the following error</p>
<pre><code class="lang-java">org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field <span class="hljs-string">'principal'</span> cannot be found on object of type <span class="hljs-string">'java.lang.Object[]'</span> - maybe not <span class="hljs-keyword">public</span> or not valid?
</code></pre>
<p>Please ensure that you have the following dependency added in your project</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.security<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-security-data<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>We looked at how to “re-use” the SecurityContext in order to be able to verify our test by querying the database after <code>mockMvc</code> request. As simple as it looks, figuring this out at a larger code base took a while to realize that this is the root cause, but luckily, the solution is pretty straight-forward.</p>
<h1 id="heading-references">References:</h1>
<ul>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/51622300/mockmvc-seems-to-be-clear-securitycontext-after-performing-request-java-lang-il">https://stackoverflow.com/questions/51622300/mockmvc-seems-to-be-clear-securitycontext-after-performing-request-java-lang-il</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/spring-projects/spring-data-mongodb/issues/2906">https://github.com/spring-projects/spring-data-mongodb/issues/2906</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/spring-projects/spring-security/issues/9565">https://github.com/spring-projects/spring-security/issues/9565</a></p>
</li>
<li><p><a target="_blank" href="https://docs.spring.io/spring-security/reference/servlet/test/mockmvc/result-handlers.html#_exporting_the_securitycontext">Exporting the SecurityContext</a></p>
</li>
</ul>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-security-securitycontext-mockmvc"><strong>GitHub</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Setting up MongoDB with replicas for local development]]></title><description><![CDATA[It's been a long time coming, but I finally came around to set up MongoDB with replicas for local development. TLDR; clone the repository, run docker…]]></description><link>https://bwgjoseph.com/setting-up-mongodb-with-replicas-for-local-development</link><guid isPermaLink="true">https://bwgjoseph.com/setting-up-mongodb-with-replicas-for-local-development</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[replicaset]]></category><category><![CDATA[development]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Docker compose]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 13 Jan 2024 19:11:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cijiWIwsMB8/upload/b0a31d2b1d23b671ba2cf5ae28115d5f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It's been a <a target="_blank" href="https://www.mongodb.com/community/forums/t/unable-to-connect-using-replicas-uri-docker-setup/10137/5">long time coming</a>, but I finally came around to set up MongoDB with replicas for local development.</p>
<p>TLDR; clone the <a target="_blank" href="https://github.com/bwgjoseph/docker-for-windows/tree/master/mongo-with-replicas">repository</a>, run <code>docker compose up -d</code>, and you are good to go!</p>
<p>If you want to know more, continue to read below.</p>
<h1 id="heading-context">Context</h1>
<p>Running MongoDB with replicas locally is useful for a number of reason, but for me, I need it to run <a target="_blank" href="https://debezium.io/">Debezium</a> for Change-Data-Capture use case which requires it.</p>
<p>I have tried a number of solutions online, and was never able to succeed for some reason, although I did come close to it a couple of times. In any case, I would like to jot down some notes for the future me.</p>
<h1 id="heading-configuration">Configuration</h1>
<h2 id="heading-keyfile">Keyfile</h2>
<p>A <a target="_blank" href="https://www.mongodb.com/docs/manual/core/security-internal-authentication/">keyfile</a> contains a shared password used as challenge and response for internal authentication.</p>
<p>To generate it, run</p>
<pre><code class="lang-powershell">openssl rand <span class="hljs-literal">-base64</span> <span class="hljs-number">756</span> &gt; mongo<span class="hljs-literal">-replica</span>.key
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Install <a target="_blank" href="https://slproweb.com/products/Win32OpenSSL.html">Windows OpenSSL</a> if you are running on Windows, otherwise, use WSL to generate it</div>
</div>

<h1 id="heading-startup">Startup</h1>
<p>To run it</p>
<pre><code class="lang-powershell">docker compose up <span class="hljs-literal">-d</span>
</code></pre>
<p>This will start up 4 containers;</p>
<ul>
<li><p>mongo-1: PRIMARY</p>
</li>
<li><p>mongo-2: SECONDARY</p>
</li>
<li><p>mongo-3: ARBITER</p>
</li>
<li><p>mongo-setup: SETUP replicas via <code>setup.sh</code></p>
</li>
</ul>
<p>The default username is <code>admin</code> and password is <code>password</code> as defined under <code>MONGO_INITDB_ROOT_USERNAME</code> and <code>MONGO_INITDB_ROOT_PASSWORD</code> environment variable respectively. And using <code>mgrs</code> as the replicaset name.</p>
<p>However, do ensure that you do not have another running instance of MongoDB (at least not on 27017 port). Personally, I have issue connecting to replicas when another instance is running. (I haven't dived deep into why yet)</p>
<p>Please wait until <code>mongo-setup</code> container is shut down before connecting to the MongoDB instance.</p>
<h1 id="heading-verify">Verify</h1>
<p>Once the setup is done, we could verify to see if everything is set up as we wanted (i.e. replicas).</p>
<pre><code class="lang-powershell"><span class="hljs-comment"># exec into the container and running bash</span>
docker exec <span class="hljs-literal">-it</span> mongo<span class="hljs-literal">-1</span> bash
<span class="hljs-comment"># connect to mongodb</span>
mongosh -<span class="hljs-literal">-host</span> mongo<span class="hljs-literal">-1</span>:<span class="hljs-number">27017</span> -<span class="hljs-literal">-username</span> admin -<span class="hljs-literal">-password</span> password
<span class="hljs-comment"># checking the replica set status</span>
rs.status()
</code></pre>
<p>The output will look something along the following</p>
<pre><code class="lang-powershell">{
  <span class="hljs-built_in">set</span>: <span class="hljs-string">'mgrs'</span>,
  date: ISODate(<span class="hljs-string">'2024-01-13T08:57:45.161Z'</span>),
  // omitted
  members: [
    {
      <span class="hljs-type">_id</span>: <span class="hljs-number">1</span>,
      <span class="hljs-type">name</span>: <span class="hljs-string">'mongo-1:27017'</span>,
      <span class="hljs-type">health</span>: <span class="hljs-number">1</span>,
      <span class="hljs-type">state</span>: <span class="hljs-number">1</span>,
      <span class="hljs-type">stateStr</span>: <span class="hljs-string">'PRIMARY'</span>,
      // <span class="hljs-type">omitted</span>
    },
    {
      <span class="hljs-type">_id</span>: <span class="hljs-number">2</span>,
      <span class="hljs-type">name</span>: <span class="hljs-string">'mongo-2:27017'</span>,
      <span class="hljs-type">health</span>: <span class="hljs-number">1</span>,
      <span class="hljs-type">state</span>: <span class="hljs-number">2</span>,
      <span class="hljs-type">stateStr</span>: <span class="hljs-string">'SECONDARY'</span>,
      // <span class="hljs-type">omitted</span>
    },
    {
      <span class="hljs-type">_id</span>: <span class="hljs-number">3</span>,
      <span class="hljs-type">name</span>: <span class="hljs-string">'mongo-3:27017'</span>,
      <span class="hljs-type">health</span>: <span class="hljs-number">1</span>,
      <span class="hljs-type">state</span>: <span class="hljs-number">7</span>,
      <span class="hljs-type">stateStr</span>: <span class="hljs-string">'ARBITER'</span>,
      // <span class="hljs-type">omitted</span>
    }
  ],
  ok: <span class="hljs-number">1</span>,
  <span class="hljs-string">'$clusterTime'</span>: {
    clusterTime: Timestamp({ t: <span class="hljs-number">1705136259</span>, i: <span class="hljs-number">1</span> }),
    signature: {
      hash: Binary.createFromBase64(<span class="hljs-string">'62HGgCSWnDEzK2Ke+7HOtI8gz00='</span>, <span class="hljs-number">0</span>),
      keyId: Long(<span class="hljs-string">'7323504381729439750'</span>)
    }
  },
  operationTime: Timestamp({ t: <span class="hljs-number">1705136259</span>, i: <span class="hljs-number">1</span> })
}
</code></pre>
<h1 id="heading-connect">Connect</h1>
<h2 id="heading-mongo-compass-wo-replicas">Mongo Compass (w/o replicas)</h2>
<p>The following URI would work</p>
<pre><code class="lang-powershell">mongodb://admin:password@localhost:<span class="hljs-number">27017</span>/?authMechanism=DEFAULT&amp;authSource=admin&amp;directConnection=true
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705171824414/db934435-cf35-4af6-afe8-e8db375efda0.png" alt class="image--center mx-auto" /></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Ensure that the <code>Direct Connection</code> option is selected</div>
</div>

<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705171848303/53f21953-5f57-4e52-82e3-9348886b31c1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-mongo-compass-w-replicas">Mongo Compass (w/ replicas)</h2>
<p>This is a little bit more tricky. You will need to add the following to your <code>hosts</code> file located in <code>C:\Windows\System32\drivers\etc</code> directory.</p>
<pre><code class="lang-powershell"><span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span> mongo<span class="hljs-literal">-1</span> mongo<span class="hljs-literal">-2</span> mongo<span class="hljs-literal">-3</span>
</code></pre>
<p>Make sure you have administrator rights to do so. Once done, the following URI would work.</p>
<pre><code class="lang-powershell">mongodb://admin:password@mongo<span class="hljs-literal">-1</span>:<span class="hljs-number">27017</span>,mongo<span class="hljs-literal">-2</span>:<span class="hljs-number">27017</span>,mongo<span class="hljs-literal">-3</span>:<span class="hljs-number">27017</span>/?authMechanism=DEFAULT&amp;authSource=admin
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705172120639/6e373448-16da-4af4-849e-677f1cdece56.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-spring-boot">Spring Boot</h2>
<p>If you are using <code>Spring Boot</code>, you can use the following URI to connect as well</p>
<pre><code class="lang-powershell">spring:
  <span class="hljs-keyword">data</span>:
    mongodb:
      <span class="hljs-comment"># either one would work</span>
      <span class="hljs-comment"># without replica</span>
      uri: mongodb://admin:password@localhost:<span class="hljs-number">27017</span>/bwgjoseph?authSource=admin
      <span class="hljs-comment"># with replica</span>
      uri: mongodb://admin:password@mongo<span class="hljs-literal">-1</span>:<span class="hljs-number">27017</span>,mongo<span class="hljs-literal">-2</span>:<span class="hljs-number">27017</span>,mongo<span class="hljs-literal">-3</span>:<span class="hljs-number">27017</span>/bwgjoseph?authSource=admin&amp;replicaSet=mgrs
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this article, I have talked about some of the things to note, such as the keyfile and how to connect to the replica set via Mongo Compass or in your Spring Boot application.</p>
<p>I hope this is useful and providing some context on why certain setup/configuration is required rather than just copying the scripts and hoping it will work for you.</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/docker-for-windows/tree/master/mongo-with-replicas"><strong>GitHub</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Lesson learned while using Taskfile to invoke PowerShell command]]></title><description><![CDATA[I recently came across TaskFile and wanted to use it to automate some of my workflows, which underlying invokes PowerShell commands. However, I faced…]]></description><link>https://bwgjoseph.com/lesson-learned-while-using-taskfile-to-invoke-powershell-command</link><guid isPermaLink="true">https://bwgjoseph.com/lesson-learned-while-using-taskfile-to-invoke-powershell-command</guid><category><![CDATA[Powershell]]></category><category><![CDATA[taskfile]]></category><category><![CDATA[automation]]></category><category><![CDATA[Scripting]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Mon, 30 Oct 2023 15:16:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4T5MTKMrjZg/upload/84191e1061736a79b0a42fc045ec9557.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-context">Context</h1>
<p>I recently came across <a target="_blank" href="https://taskfile.dev/">TaskFile</a> and wanted to use it to automate some of my workflows, which underlying invokes PowerShell commands. However, I faced several errors while doing so, and this post is to reflect on it, and hopefully help myself (in the future), or someone else.</p>
<p>To be clear, this has nothing to do with <code>TaskFile</code>.</p>
<h1 id="heading-current-state">Current State</h1>
<p>I wrote a super simple <code>taskfile.yml</code> which invokes my PowerShell script.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">tasks:</span>
  <span class="hljs-attr">dl-apps:</span>
    <span class="hljs-attr">platforms:</span> [<span class="hljs-string">windows</span>]
    <span class="hljs-attr">dir:</span> <span class="hljs-string">/apps</span>
    <span class="hljs-attr">cmds:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">powershell</span> <span class="hljs-string">-File</span> <span class="hljs-string">apps-downloads.ps1</span>
</code></pre>
<h2 id="heading-attempt-1">Attempt #1</h2>
<p>I try to run the <code>task</code> command, but encounter the following error message.</p>
<pre><code class="lang-powershell">&gt; task dl<span class="hljs-literal">-apps</span>
task: [<span class="hljs-type">dl</span>-<span class="hljs-type">apps</span>] powershell <span class="hljs-operator">-File</span> apps<span class="hljs-literal">-downloads</span>.ps1
<span class="hljs-built_in">Import-Module</span> : The specified module <span class="hljs-string">'oh-my-posh'</span> was not loaded because no valid module file was found <span class="hljs-keyword">in</span> any module directory.
At C:\Users\Joseph\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:<span class="hljs-number">2</span> char:<span class="hljs-number">1</span>
+ <span class="hljs-built_in">Import-Module</span> <span class="hljs-built_in">oh</span><span class="hljs-literal">-my</span><span class="hljs-literal">-posh</span>
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (<span class="hljs-built_in">oh</span><span class="hljs-literal">-my</span><span class="hljs-literal">-posh</span>:String) [<span class="hljs-built_in">Import-Module</span>], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

<span class="hljs-built_in">Import-PowerShellDataFile</span> : The term <span class="hljs-string">'Import-PowerShellDataFile'</span> is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or <span class="hljs-keyword">if</span> a path was
included, verify that the path is correct and <span class="hljs-keyword">try</span> again.
At C:\Users\Joseph\Documents\PowerShell\Modules\Terminal<span class="hljs-literal">-Icons</span>\<span class="hljs-number">0.9</span>.<span class="hljs-number">0</span>\Terminal<span class="hljs-literal">-Icons</span>.psm1:<span class="hljs-number">210</span> char:<span class="hljs-number">33</span>
+         <span class="hljs-variable">$hash</span>.Add(<span class="hljs-variable">$_</span>.Basename, (<span class="hljs-built_in">Import-PowerShellDataFile</span> <span class="hljs-variable">$_</span>.FullName ...
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (<span class="hljs-built_in">Import-PowerShellDataFile</span>:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>It wasn't immediately obvious to me what the problem was, so I attempted to figure out what was causing it.</p>
<h3 id="heading-wrong-powershell-profile-invoked">Wrong PowerShell Profile invoked?</h3>
<p>Running this command would show the current profiles</p>
<pre><code class="lang-powershell">&gt; <span class="hljs-variable">$PROFILE</span> | <span class="hljs-built_in">Select-Object</span> *

AllUsersAllHosts       : C:\Program Files\PowerShell\<span class="hljs-number">7</span>\profile.ps1
AllUsersCurrentHost    : C:\Program Files\PowerShell\<span class="hljs-number">7</span>\Microsoft.PowerShell_profile.ps1
CurrentUserAllHosts    : C:\Users\Joseph\Documents\PowerShell\profile.ps1
CurrentUserCurrentHost : C:\Users\Joseph\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Length                 : <span class="hljs-number">69</span>
</code></pre>
<p>Only <code>CurrentUserCurrentHost</code> is valid as I did not find any profiles (.ps1) file</p>
<blockquote>
<p>I later realized that it did not display the list of profiles for legacy PowerShell, those in &lt;path&gt;\WindowsPowerShell\</p>
</blockquote>
<p>My <code>Microsoft.PowerShell_profile.ps1</code> contains the following</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Import-Module</span> Terminal<span class="hljs-literal">-Icons</span>
<span class="hljs-built_in">Import-Module</span> PSReadLine
<span class="hljs-built_in">Set-PSReadLineOption</span> <span class="hljs-literal">-PredictionSource</span> <span class="hljs-built_in">History</span>
<span class="hljs-built_in">Set-PSReadLineOption</span> <span class="hljs-literal">-PredictionViewStyle</span> ListView
<span class="hljs-built_in">Set-PSReadLineOption</span> <span class="hljs-literal">-EditMode</span> Windows

<span class="hljs-built_in">Set-Alias</span> k kubectl
<span class="hljs-built_in">Set-Alias</span> mk minikube

<span class="hljs-built_in">oh</span><span class="hljs-literal">-my</span><span class="hljs-literal">-posh</span> init pwsh -<span class="hljs-literal">-config</span> <span class="hljs-string">"<span class="hljs-variable">$env:POSH_THEMES_PATH</span>\night-owl.omp.json"</span> | <span class="hljs-built_in">Invoke-Expression</span>
</code></pre>
<p>There was no indication of <code>posh-git</code> module. I have already <a target="_blank" href="https://bwgjoseph.com/installing-oh-my-posh-using-winget">removed</a> it and changed it to using the <code>oh-my-posh</code> installation method rather than using the PowerShell module.</p>
<p>So I'm quite confused about why this happens.</p>
<h3 id="heading-wrong-posh-git-invoked">Wrong posh-git invoked?</h3>
<p>So I ran the following command to see if there's <code>posh-git</code> and it does exist</p>
<pre><code class="lang-powershell">&gt; <span class="hljs-built_in">Get-module</span> <span class="hljs-literal">-ListAvailable</span>

    Directory: C:\Users\Joseph\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     <span class="hljs-number">1.0</span>.<span class="hljs-number">0</span>                 posh<span class="hljs-literal">-git</span>                            Desk      {<span class="hljs-built_in">Add-PoshGitToProfile</span>, <span class="hljs-built_in">Expand-GitCommand</span>, <span class="hljs-built_in">Format-GitBranchName</span>, <span class="hljs-built_in">Get-GitBranchStatusColor</span>…}
Script     <span class="hljs-number">2.2</span>.<span class="hljs-number">1</span>      rc1        PSReadLine                          Desk      {<span class="hljs-built_in">Get-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Set-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Remove-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Get-PSReadLineOption</span>…}
Script     <span class="hljs-number">0.9</span>.<span class="hljs-number">0</span>                 Terminal<span class="hljs-literal">-Icons</span>                      Desk      {<span class="hljs-built_in">Add-TerminalIconsColorTheme</span>, <span class="hljs-built_in">Add-TerminalIconsIconTheme</span>, <span class="hljs-built_in">Format-TerminalIcons</span>, <span class="hljs-built_in">Get-TerminalIconsColorTheme</span>…}
Script     <span class="hljs-number">1.1</span>.<span class="hljs-number">13</span>                z                                   Desk      {z, cdX, popdX, pushdX}
</code></pre>
<p>That's rather interesting as I thought I had already removed it. So I uninstalled it again</p>
<pre><code class="lang-powershell">&gt; <span class="hljs-built_in">Uninstall-Module</span> posh<span class="hljs-literal">-git</span>
</code></pre>
<p>After which, I verified that it was indeed removed.</p>
<pre><code class="lang-powershell">&gt; <span class="hljs-built_in">Get-module</span> <span class="hljs-literal">-ListAvailable</span>

    Directory: C:\Users\Joseph\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     <span class="hljs-number">2.2</span>.<span class="hljs-number">1</span>      rc1        PSReadLine                          Desk      {<span class="hljs-built_in">Get-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Set-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Remove-PSReadLineKeyHandler</span>, <span class="hljs-built_in">Get-PSReadLineOption</span>…}
Script     <span class="hljs-number">0.9</span>.<span class="hljs-number">0</span>                 Terminal<span class="hljs-literal">-Icons</span>                      Desk      {<span class="hljs-built_in">Add-TerminalIconsColorTheme</span>, <span class="hljs-built_in">Add-TerminalIconsIconTheme</span>, <span class="hljs-built_in">Format-TerminalIcons</span>, <span class="hljs-built_in">Get-TerminalIconsColorTheme</span>…}
Script     <span class="hljs-number">1.1</span>.<span class="hljs-number">13</span>                z                                   Desk      {z, cdX, popdX, pushdX}
</code></pre>
<h2 id="heading-attempt-2">Attempt #2</h2>
<p>With that, I tried to run the <code>task</code> command again, however, it is still throwing the same error.</p>
<pre><code class="lang-powershell">&gt; task dl<span class="hljs-literal">-apps</span>
task: [<span class="hljs-type">dl</span>-<span class="hljs-type">apps</span>] powershell <span class="hljs-operator">-File</span> apps<span class="hljs-literal">-downloads</span>.ps1
<span class="hljs-built_in">Import-Module</span> : The specified module <span class="hljs-string">'posh-git'</span> was not loaded because no valid module file was found <span class="hljs-keyword">in</span> any module directory.
At C:\Users\Joseph\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:<span class="hljs-number">1</span> char:<span class="hljs-number">1</span>
+ <span class="hljs-built_in">Import-Module</span> posh<span class="hljs-literal">-git</span>
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (posh<span class="hljs-literal">-git</span>:String) [<span class="hljs-built_in">Import-Module</span>], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
</code></pre>
<p>Since I just uninstalled <code>posh-git</code>, and have verified it. This error shouldn't happen anymore. So I printed out the content of the file which in hindsight, I should have done in the first place.</p>
<pre><code class="lang-powershell">&gt; <span class="hljs-built_in">cat</span> C:\Users\Joseph\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
</code></pre>
<p>And this is the output</p>
<pre><code class="lang-bash">&gt; cat C:\Users\Joseph\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Import-Module posh-git
Import-Module oh-my-posh
Import-Module Terminal-Icons
Import-Module PSReadLine
Import-Module z
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineOption -EditMode Windows
Set-PoshPrompt Paradox
</code></pre>
<p>Which then made me realize that I was looking at two different files <strong>right from the start</strong>!</p>
<pre><code class="lang-bash"><span class="hljs-comment"># PS - Legacy &lt; 5.x</span>
C:\Users\Joseph\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
<span class="hljs-comment"># PS - Current &gt; 6.x</span>
C:\Users\Joseph\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
</code></pre>
<p>So there are two different versions of the directory, and running for different PowerShell versions.</p>
<h1 id="heading-solution">Solution</h1>
<p>Knowing my mistake, it was quite simple to fix it. I just had to switch to using <code>pwsh</code> command. But I guess this is also a good lesson for me to always take closer look at the differences between versions.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">tasks:</span>
  <span class="hljs-attr">dl-apps:</span>
    <span class="hljs-attr">platforms:</span> [<span class="hljs-string">windows</span>]
    <span class="hljs-attr">dir:</span> <span class="hljs-string">/apps</span>
    <span class="hljs-attr">cmds:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">pwsh</span> <span class="hljs-string">-File</span> <span class="hljs-string">apps-downloads.ps1</span>
</code></pre>
<p>References:</p>
<ul>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.3#powershell-executable-changes">https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.3#powershell-executable-changes</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Reclaim disk space used by Docker Desktop (WSL2)]]></title><description><![CDATA[I was always out of disk space in my C drive, and even though I clear my stuff often, I notice that my space is never reclaimed, instead, it kept going…]]></description><link>https://bwgjoseph.com/reclaim-disk-space-used-by-docker-desktop-wsl2</link><guid isPermaLink="true">https://bwgjoseph.com/reclaim-disk-space-used-by-docker-desktop-wsl2</guid><category><![CDATA[Docker]]></category><category><![CDATA[wsl2]]></category><category><![CDATA[Windows]]></category><category><![CDATA[hyper-v]]></category><category><![CDATA[disk space]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 21 Oct 2023 15:47:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/HSACbYjZsqQ/upload/5fce9362ba881b07fc96fe36cf1311aa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-problem">Problem</h1>
<p>I was always out of disk space in my C drive, and even though I clear my stuff often, I notice that my space is never reclaimed, instead, it kept going down.</p>
<p>I used <a target="_blank" href="https://diskanalyzer.com/">WizTree</a> to view which file is taking up my disk space, and I noticed this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697900944923/e270efcb-3499-444d-a848-c670ff20c30c.png" alt class="image--center mx-auto" /></p>
<p>Notice that in <code>%LOCALAPPDATA%\Docker\wsl\data</code>, there is a file <code>ext4.vhdx</code> that is taking up <code>64.6gb</code> of space, around <code>14%</code> of my total disk space.</p>
<blockquote>
<p>Docker Desktop for Windows uses WSL2 to manage all images and keep them in <code>ext4.vhdx</code></p>
</blockquote>
<p>So to reclaim the space, I tried to delete the docker images via <code>Docker Desktop</code> manually, but the space was not reclaimed even though I deleted most of the unused images.</p>
<p>Based on <code>portainer</code>, I am currently only using <code>4.1gb</code> of space where before the clean-up, I am using around <code>20+gb</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697901445817/56496467-20ab-4065-86e4-01cfed134526.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-solution-optimize-vhd">Solution - <strong>Optimize-VHD</strong></h1>
<p>Hyper-V has a command <code>Optimize-VHD</code> that optimizes the allocation of space used by virtual hard disk files. In short, it helps to shrink the space used by <code>Docker Desktop</code>.</p>
<p>To do so, exit <code>Docker Desktop</code>, and shutdown WSL by running</p>
<pre><code class="lang-bash">wsl --shutdown
</code></pre>
<p>Give it a minute, and run <code>wsl -l -v</code> and the distro should be in <code>stopped</code> state.</p>
<pre><code class="lang-bash"> wsl -l -v
  NAME                    STATE           VERSION
* Ubuntu                  Stopped         2
  docker-desktop          Stopped         2
  docker-desktop-data     Stopped         2
  rancher-desktop         Stopped         2
  rancher-desktop-data    Stopped         2
</code></pre>
<p>Navigate to the directory that stores <code>ext4.vhdx</code>, and run the following command</p>
<pre><code class="lang-bash">optimize-vhd -Path .\ext4.vhdx -Mode full
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697901726031/4e363714-73d2-46db-ad9f-9fa9c0042e68.png" alt class="image--center mx-auto" /></p>
<p>Give it some time to complete, it took around 5 min for me.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697901981839/96ae0984-0d00-4b19-930c-6e8b4202daea.png" alt class="image--center mx-auto" /></p>
<p>Viola! It reclaims nearly <code>40gb</code> of disk space for me.</p>
<p>It's a chore to keep reclaiming manually, but I've learned that WSL has a <a target="_blank" href="https://devblogs.microsoft.com/commandline/windows-subsystem-for-linux-september-2023-update/">new update</a> recently where it comes with <code>Sparse VHD</code>, a feature that automatically shrinks the WSL virtual hard disk (VHD) as you use it. If you are already using the latest version of WSL (currently in pre-release as of writing), then you can run the following command to enable it.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># wsl --manage &lt;distro&gt; --set-sparse &lt;true/false&gt;</span>
wsl --manage Ubuntu --set-sparse <span class="hljs-literal">true</span>
</code></pre>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/optimize-vhd?view=windowsserver2022-ps">https://learn.microsoft.com/en-us/powershell/module/hyper-v/optimize-vhd?view=windowsserver2022-ps</a></p>
</li>
<li><p><a target="_blank" href="https://www.hanselman.com/blog/shrink-your-wsl2-virtual-disks-and-docker-images-and-reclaim-disk-space">https://www.hanselman.com/blog/shrink-your-wsl2-virtual-disks-and-docker-images-and-reclaim-disk-space</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Maven 101 - Multi-Module]]></title><description><![CDATA[This is a follow-up post to Maven 101 - Basics. If you have not read that, I strongly suggest reading that before continuing on this. In this post, I will…]]></description><link>https://bwgjoseph.com/maven-101-multi-module</link><guid isPermaLink="true">https://bwgjoseph.com/maven-101-multi-module</guid><category><![CDATA[maven]]></category><category><![CDATA[Java]]></category><category><![CDATA[Build tool]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 07 Oct 2023 15:23:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695141436420/af1bdbc0-bf5f-417d-aeb4-838f2bae1d5e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>This is a follow-up post to <a target="_blank" href="https://bwgjoseph.com/maven-101-basics">Maven 101 - Basics</a>. If you have not read that, I strongly suggest reading that before continuing on this.</p>
<p>In this post, I will be focusing on using <code>Maven</code> with <code>multi-module</code> setup using the following structure.</p>
<p>First, let's take a look at the project structure that will be used throughout this post.</p>
<pre><code class="lang-bash">root/
├── pom.xml
└── project/
    ├── pom.xml
    ├── core/
    │   └── pom.xml
    ├── project-parent/
    │   └── pom.xml
    └── web/
        └── pom.xml
</code></pre>
<p><code>root/pom.xml</code> and <code>root/project/pom.xml</code> will be configured as <code>aggregate POM</code> while <code>root/project/project-parent/pom.xml</code> will be configured as <code>parent POM</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693735948980/5480e69b-7276-4fd1-8aab-ac3366705e04.png" alt class="image--center mx-auto" /></p>
<p>The diagram above shows the relationship between each module</p>
<h1 id="heading-maven-reactor">Maven Reactor</h1>
<p>It is important to understand what <code>Maven Reactor</code> is, and what it does before diving into <code>multi-module</code> setup.</p>
<p><code>Maven Reactor</code> is the key mechanism that handles the <code>multi-module</code> project and does the following:</p>
<ul>
<li><p>Collects all the available modules to build</p>
</li>
<li><p>Sorts the projects into the correct build order</p>
</li>
<li><p>Builds the selected projects in order</p>
</li>
</ul>
<blockquote>
<p>Taken directly from <a target="_blank" href="https://maven.apache.org/guides/mini/guide-multiple-modules.html">Maven site</a></p>
</blockquote>
<p><code>Maven Reactor</code> figures out the order of the modules by using <code>directed acyclic graph (DAG)</code> to determine the build order of the project.</p>
<p>Given the project structure above, if we compile the project, this will be the output.</p>
<pre><code class="lang-bash">&gt; ./mvnw clean compile
[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] maven-101-multi-module-project-core                                [jar]
[INFO] maven-101-multi-module-project-web                                 [jar]
[INFO] maven-101-multi-module-project-aggregator                          [pom]
[INFO] maven-101-multi-module                                             [pom]
[INFO]
[INFO] ---------&lt; com.bwgjoseph:maven-101-multi-module-project-core &gt;----------
[INFO] Building maven-101-multi-module-project-core 0.0.1-SNAPSHOT        [1/4]
[INFO]   from project\core\pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
</code></pre>
<p>As shown in the logs above, it shows the sequential order of the module to be built.</p>
<blockquote>
<p>Remember that <code>web</code> depends-on <code>core</code> so it ensures <code>core</code> builds first</p>
</blockquote>
<h2 id="heading-command-line-options">Command Line Options</h2>
<p>The following command line switches are available:</p>
<ul>
<li><p><code>--resume-from | -rf</code> - resumes a reactor from the specified project (e.g. when it fails in the middle)</p>
</li>
<li><p><code>--also-make | -am</code> - build the specified projects and any of their dependencies in the reactor</p>
</li>
<li><p><code>--also-make-dependents | -amd</code> - build the specified projects and any that depend on them</p>
</li>
<li><p><code>--fail-fast | -ff</code> - the default behavior - whenever a module build fails, stop the overall build immediately</p>
</li>
<li><p><code>--fail-at-end</code> - if a particular module build fails, continue the rest of the reactor and report all failed modules at the end instead</p>
</li>
<li><p><code>--non-recursive</code> - do not use a reactor build, even if the current project declares modules and just build the project in the current directory</p>
</li>
</ul>
<blockquote>
<p>Shamelessly plug off <a target="_blank" href="https://maven.apache.org/guides/mini/guide-multiple-modules.html#command-line-options">Maven site</a></p>
</blockquote>
<p>These are very useful commands to know while working with <code>multi-module</code> project setups.</p>
<p>I have an issue using <code>-rf</code> when used along with <code>-f/-pl/-am</code> flags. Imagine while compiling, it fails on <code>web</code>, and if I fixed the issue and wanted to resume, I could have resumed from <code>web</code> rather than running all over again using this command. But for some reason which I can't quite figure out what's the correct command to run to make sure it works correctly</p>
<pre><code class="lang-bash">./mvnw clean compile -f project -rf :web
</code></pre>
<h1 id="heading-type-of-pom">Type of POM</h1>
<h2 id="heading-aggregate-pom">Aggregate POM</h2>
<blockquote>
<p>Also known as <code>Project Aggregation</code></p>
</blockquote>
<p>This POM file specifies which subprojects (or modules) to build and builds them in the specified order, managed by <code>The Reactor</code>.</p>
<p>Below is the current project setup aggregator pom file.</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- root --&gt;</span>
<span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>maven-101-multi-module<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Maven 101 - Multi Module<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">packaging</span>&gt;</span>pom<span class="hljs-tag">&lt;/<span class="hljs-name">packaging</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">modules</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>project<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">modules</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- root/project --&gt;</span>
<span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-aggregator<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>maven-101-multi-module-project-aggregator<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Maven 101 - Multi Module<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">packaging</span>&gt;</span>pom<span class="hljs-tag">&lt;/<span class="hljs-name">packaging</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">modules</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>core<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>web<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">modules</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>The key difference between this and the <code>Simple POM</code> is that it has</p>
<ul>
<li><p>packaging</p>
<ul>
<li>define as either jar/pom (default is jar)</li>
</ul>
</li>
<li><p>modules</p>
<ul>
<li>listing of all the modules of the project</li>
</ul>
</li>
</ul>
<p>This is useful to group similar/related modules under this <code>Aggregated POM</code> so that one can run the command against this <code>POM</code>, and all the child modules will be triggered.</p>
<h2 id="heading-parent-pom">Parent POM</h2>
<blockquote>
<p>Also known as <code>Project Inheritance</code></p>
</blockquote>
<p>Similar to how <code>Simple POM</code> inherits from <code>Super POM</code>. We can define our own <code>Parent POM</code> with a set of configurations that can be shared across multiple modules.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.1.3<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">relativePath</span>/&gt;</span> <span class="hljs-comment">&lt;!-- lookup parent from repository --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>maven-101-multi-module-project-parent<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Maven 101 - Multi Module<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">packaging</span>&gt;</span>pom<span class="hljs-tag">&lt;/<span class="hljs-name">packaging</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>17<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">error-handling-spring-boot-starter.version</span>&gt;</span>4.2.0<span class="hljs-tag">&lt;/<span class="hljs-name">error-handling-spring-boot-starter.version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.wimdeblauwe<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>error-handling-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${error-handling-spring-boot-starter.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- omitted --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">pluginManagement</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">excludes</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">exclude</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.projectlombok<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>lombok<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">exclude</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">excludes</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">pluginManagement</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.jacoco<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jacoco-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.8.10<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>In <code>root/project/project-parent</code>, there's only 1 file, and that's <code>pom.xml</code> which is used to inherit the individual modules. For example, in the <code>core module</code>,</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- inherits from project-parent --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">relativePath</span>&gt;</span>../project-parent<span class="hljs-tag">&lt;/<span class="hljs-name">relativePath</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>maven-101-multi-module-project-core<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Maven 101 - Multi Module<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>We declare that the <code>core module</code> inherits from <code>project-parent</code> POM.</p>
<p>This makes it easier to manage configuration, especially for dependencies (pinning) and plugins.</p>
<h2 id="heading-aggregate-vs-inheritance">Aggregate vs Inheritance</h2>
<p>In short, using <code>Aggregate</code> means the parent <strong>knows</strong> who are the children while using <code>Inheritance</code> means the parent <strong>doesn't know</strong> who are the children.</p>
<p>Running a command against <code>Aggregate</code> POM will invoke its children, but not for <code>Inheritance</code> POM.</p>
<p>You don't have to choose, as both can be used together in a single project.</p>
<p>It is very common for developers to mix both types of POM into a single <code>pom.xml</code> file which is fine. However, my personal opinion is to separate them if possible, especially for slightly more complex project structures. Because separating them also means separating the concern of building the project, where I can use the same <code>aggregator</code> to build a group of modules but they don't necessarily share the same configuration.</p>
<h1 id="heading-dependency-management">Dependency Management</h1>
<p>It is important to understand the difference between using <code>dependencyManagement</code> and <code>dependencies</code>.</p>
<p><code>dependencyManagement</code> and <code>dependencies</code> are both used to define dependency information, versioning, as well as configuration. The difference is <code>dependencyManagement</code> does not add an actual dependency to the project/module. Whereas, <code>dependencies</code> will add an actual dependency.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencyManagement</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.wimdeblauwe<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>error-handling-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.2.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencyManagement</span>&gt;</span>
</code></pre>
<p>If we add the dependency to <code>dependencyManagement</code>, we will not be able to import and use the library. Until we explicitly add to under <code>dependencies</code> tag.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.wimdeblauwe<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>error-handling-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
</code></pre>
<p>Note that there is no need to declare the version anymore since it is now managed via <code>dependencyManagement</code>.</p>
<h1 id="heading-plugin-management">Plugin Management</h1>
<p>The concept is similar to <code>Dependency Management</code> as described above.</p>
<p>Plugin dependency configurations are usually a little bit more involved, and complex. Hence, being able to define once, and apply for all modules makes it much easier to re-use, and less error-prone.</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- parent pom --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">pluginManagement</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.jacoco<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jacoco-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.8.10<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">pluginManagement</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
</code></pre>
<p>Would you rather declare this once at the <code>parent-pom</code> and reuse it across all inherited modules? Or declare it at every child <code>pom.xml</code> like what is shown below?</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- child pom --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.jacoco<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jacoco-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
</code></pre>
<p>There is no need to declare the version, configuration, execution, or any other properties, unless, the intention is to overwrite it.</p>
<h1 id="heading-building-project">Building Project</h1>
<p>How to use <code>-am</code> to build the project without installing the dependency modules</p>
<blockquote>
<p>-am: Builds the specified modules, and any of their dependencies in the reactor.</p>
</blockquote>
<p>We know that <code>web</code> depends on <code>core</code>, and if we run the following command</p>
<pre><code class="lang-bash">./mvnw package -f project -pl core
</code></pre>
<p>We get the following error</p>
<pre><code class="lang-bash">&gt; ./mvnw package -f project -pl web
[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO]
[INFO] ----------&lt; com.bwgjoseph:maven-101-multi-module-project-web &gt;----------
[INFO] Building maven-101-multi-module-project-web 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[WARNING] The POM <span class="hljs-keyword">for</span> com.bwgjoseph:maven-101-multi-module-project-core:jar:0.0.1-SNAPSHOT is missing, no dependency information available
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.881 s
[INFO] Finished at: 2023-09-03T23:35:36+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project maven-101-multi-module-project-web: Could not resolve dependencies <span class="hljs-keyword">for</span> project com.bwgjoseph:maven-101-multi-module-project-web:jar:0.0.1-SNAPSHOT: The following artifacts could not be resolved: com.bwgjoseph:maven-101-multi-module-project-core:jar:0.0.1-SNAPSHOT (absent): Could not find artifact com.bwgjoseph:maven-101-multi-module-project-core:jar:0.0.1-SNAPSHOT -&gt; [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to <span class="hljs-built_in">enable</span> full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please <span class="hljs-built_in">read</span> the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
</code></pre>
<p>That's because it's trying to find <code>com.bwgjoseph:maven-101-multi-module-project-core:jar:0.0.1-SNAPSHOT</code> either in local or remote repositories which is not available since we did not install locally or deploy it.</p>
<p>To overcome/resolve it, we can deploy it locally first by running</p>
<pre><code class="lang-bash">./mvnw install -f project -pl core
</code></pre>
<p>Which would have made it available locally, or we can actually use <code>-am</code> (also-make) command to build the dependent project first. This way, there is no need to ensure the dependent module is first deployed locally/remotely.</p>
<pre><code class="lang-bash">./mvnw package -f project -pl web -am
</code></pre>
<pre><code class="lang-bash">[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] maven-101-multi-module-project-core                                [jar]
[INFO] maven-101-multi-module-project-web                                 [jar]
[INFO]
[INFO] ---------&lt; com.bwgjoseph:maven-101-multi-module-project-core &gt;----------
[INFO] Building maven-101-multi-module-project-core 0.0.1-SNAPSHOT        [1/2]
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
// omitted
[INFO] --- jar:3.3.0:jar (default-jar) @ maven-101-multi-module-project-web ---
[INFO] Building jar: Z:\Development\workspace\github\bwgjoseph\tutorials\maven-101-multi-module\project\web\target\maven-101-multi-module-project-web-0.0.1-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary <span class="hljs-keyword">for</span> maven-101-multi-module-project-core 0.0.1-SNAPSHOT:
[INFO]
[INFO] maven-101-multi-module-project-core ................ SUCCESS [ 21.384 s]
[INFO] maven-101-multi-module-project-web ................. SUCCESS [ 13.848 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  36.158 s
[INFO] Finished at: 2023-09-03T23:38:58+08:00
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>We can see that it now build <code>core</code> project before <code>web</code> module.</p>
<h1 id="heading-running-test">Running Test</h1>
<h2 id="heading-all-test">All Test</h2>
<p>To run all tests for all modules under <code>/project</code>, run the following command</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project
</code></pre>
<blockquote>
<p>-f: Select an alternative POM file or directory containing a POM file</p>
<p>This also gives us the benefit of having a single maven wrapper at the root directory but being able to run any POM</p>
</blockquote>
<p>It should give you the following result</p>
<pre><code class="lang-bash">&gt; ./mvnw <span class="hljs-built_in">test</span> -f project
[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] maven-101-multi-module-project-core                                [jar]
[INFO] maven-101-multi-module-project-web                                 [jar]
[INFO] maven-101-multi-module-project-aggregator                          [pom]
[INFO]
[INFO] ---------&lt; com.bwgjoseph:maven-101-multi-module-project-core &gt;----------
[INFO] Building maven-101-multi-module-project-core 0.0.1-SNAPSHOT        [1/3]
[INFO]   from core\pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
</code></pre>
<h2 id="heading-specific-test-class">Specific Test Class</h2>
<p>If wish to run a specific test class, then you can filter it using <code>-Dtest</code> parameter.</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -Dtest=SampleTests
</code></pre>
<p>Note that if we are on a multi-module, it is better to indicate a specific module, otherwise, it might fail if the test class does not exist in any other submodule.</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=SampleTests
</code></pre>
<blockquote>
<p>-pl: select a specific set of projects to apply your goal</p>
</blockquote>
<pre><code class="lang-bash">&gt; ./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=SampleTests
[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO]
[INFO] ---------&lt; com.bwgjoseph:maven-101-multi-module-project-core &gt;----------
[INFO] Building maven-101-multi-module-project-core 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
// omitted
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.bwgjoseph.multimodule.SampleTests
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.432 s - <span class="hljs-keyword">in</span> com.bwgjoseph.multimodule.SampleTests
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- jacoco:0.8.10:report (report) @ maven-101-multi-module-project-core ---
[INFO] Loading execution data file Z:\Development\workspace\github\bwgjoseph\tutorials\maven-101-multi-module\project\core\target\jacoco.exec
[INFO] Analyzed bundle <span class="hljs-string">'maven-101-multi-module-project-core'</span> with 5 classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  7.193 s
[INFO] Finished at: 2023-09-03T23:32:41+08:00
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>To run multiple classes, separate them with <code>comma</code></p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=SampleTests,AnotherSampleTests
</code></pre>
<h2 id="heading-specific-method">Specific Method</h2>
<p>If wish to run a specific method within a class, use <code>#</code> like such</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=SampleTests<span class="hljs-comment">#test1</span>
</code></pre>
<p>Similarly, you can chain up other test from other class using</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=<span class="hljs-string">"SampleTests#test1,AnotherSampleTests#test2"</span>
</code></pre>
<blockquote>
<p>Remember to wrap it with quotes</p>
</blockquote>
<p>It is also possible to provide wildcards such as</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dtest=SampleTests<span class="hljs-comment">#test*</span>
</code></pre>
<p>This will run all test method name that starts with <code>test</code></p>
<h2 id="heading-specific-groups">Specific Groups</h2>
<p>If wish to run through a group of tests via <code>@Tags</code> or <code>@Tag</code> annotation</p>
<pre><code class="lang-java"><span class="hljs-meta">@Tag("sample")</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SampleTests</span> </span>{}
</code></pre>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span> -f project -pl core -Dgroups=sample
</code></pre>
<blockquote>
<p>It is also possible to exclude using <code>-DexcludedGroups</code></p>
</blockquote>
<h1 id="heading-jacoco-plugin">JaCoCo Plugin</h1>
<p>The JaCoCo Maven plug-in provides the JaCoCo runtime agent to your tests and allows basic report creation.</p>
<blockquote>
<p>Quoted directly from <a target="_blank" href="https://www.eclemma.org/jacoco/trunk/doc/maven.html">jacoco-maven</a></p>
</blockquote>
<p>In this section, I will be showing the difference between generating jacoco report in a single module and consolidating across various modules.</p>
<h2 id="heading-single-module">Single Module</h2>
<p>To generate code coverage, I added <code>jacoco-maven-plugin</code> to one of the module</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.jacoco<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jacoco-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.8.10<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>prepare-agent<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p><code>prepare-agent</code> goal is set up to record the execution data such as lines executed. The execution data file is written to <code>/target/jacoco.exec</code>.</p>
<p><code>report</code> goal is to read the file - <code>jacoco.exec</code>, and write the report and output to <code>/target/site/jacoco/index.html</code></p>
<p>Once added, run the following</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">test</span>
</code></pre>
<p>Which works, but this is a bit more tricky for <code>multi-module</code> because <code>jacoco</code> would have generated a report for each of the individual modules but not as an aggregated report.</p>
<blockquote>
<p>Navigate to <code>./project/core/target/site/jacoco/index.html</code> to view the report</p>
</blockquote>
<h2 id="heading-multi-module">Multi Module</h2>
<p>In a multi-module setup, having an aggregated jacoco report across all submodules is much better for reporting purposes. To do so, I created an <code>aggregated-report</code> submodule to house the aggregated report</p>
<p>In <code>aggregated-report</code> pom.xml</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- add dependencies on all the modules that we want to include --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-multi-module-project-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>

<span class="hljs-comment">&lt;!-- define report-aggregate for jacoco --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.jacoco<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jacoco-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.8.10<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>report<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>prepare-package<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>report-aggregate<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p>Note that, we do not change the <code>jacoco</code> pom configuration that we defined previously in <code>/project-parent/pom.xml</code>. This configuration combines the reports so that running <code>./mvnw package -f project -pl aggregated-report -am</code> will create the aggregated report view</p>
<p>But.... this will trigger all the dependent submodules to run the <code>package</code> lifecycle again to collect the reports.</p>
<p>Is there a better way? Yes! By running the <code>report-aggregate</code> goal directory which will collect the jacoco result from the various dependency submodules instead of triggering them to run again (provided that those individual module has already run the report).</p>
<pre><code class="lang-bash">./mvnw jacoco:report-aggregate -f project -pl aggregated-report -am
</code></pre>
<p>The number of reports that will be aggregated within <code>aggregated-report</code> submodule depends on which dependency you have included.</p>
<p>The <code>aggregated-report</code> submodule can be standalone, meaning it does not have to point to <code>/project-parent</code> as its parent pom (which is very often shown in examples in the internet).</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>While most of the examples are shown with <code>multi-module</code> setup, most of them should be the same for normal single-module setup, just remove/ignore <code>-pl or -f or -am</code> argument (in most cases).</p>
<p><code>Maven</code> has pretty good support for <code>multi-module</code> setup (with an even better one coming from Maven v4), but I think that it isn't very well documented, at least in terms of samples that one could refer to and rely on.</p>
<p>By using it myself, I have gained much more understanding about <code>Maven multi-module</code> setup and able to slowly take advantage of it bit by bit.</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/maven-101-multi-module"><strong>GitHub</strong></a></p>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://maven.apache.org/guides/mini/guide-multiple-modules.html">https://maven.apache.org/guides/mini/guide-multiple-modules.html</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/7612309/maven-non-resolvable-parent-pom">https://stackoverflow.com/questions/7612309/maven-non-resolvable-parent-pom</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/9500480/install-parent-pom-without-building-child-modules">https://stackoverflow.com/questions/9500480/install-parent-pom-without-building-child-modules</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/13031219/how-to-configure-multi-module-maven-sonar-jacoco-to-give-merged-coverage-rep">https://stackoverflow.com/questions/13031219/how-to-configure-multi-module-maven-sonar-jacoco-to-give-merged-coverage-rep</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Maven 101 - Basics]]></title><description><![CDATA[Maven is used to manage and build any Java-based project. It provides an opinionated way of the project structure, managing dependencies, building projects…]]></description><link>https://bwgjoseph.com/maven-101-basics</link><guid isPermaLink="true">https://bwgjoseph.com/maven-101-basics</guid><category><![CDATA[maven]]></category><category><![CDATA[Java]]></category><category><![CDATA[apache]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 16 Sep 2023 18:20:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1694850051505/a7cb5b4c-1beb-4b69-b8ea-89be18f621c8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p><code>Maven</code> is used to manage and build any Java-based project. It provides an opinionated way of the project structure, managing dependencies, building projects and deploying the artifacts.</p>
<h1 id="heading-project-object-model-pom">Project Object Model (POM)</h1>
<p><code>POM</code> stands for <code>Project Object Model</code>. This is the core of <code>Maven</code> and it is declared using <code>XML</code>.</p>
<p>Let's take a look at a sample <code>pom.xml</code>.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Required --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- This 3 properties also known as Coordinates --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-basic<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- Optional --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>maven-101-basic<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Maven 101 Basics<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>It contains the following key components:</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">-</span> modelVersion
<span class="hljs-bullet">-</span> Coordinates
<span class="hljs-bullet">  -</span> groupId, artifactId, version
<span class="hljs-bullet">-</span> name
<span class="hljs-bullet">-</span> description
</code></pre>
<p><code>pom</code> file always exists at the root of the project directory.</p>
<pre><code class="lang-bash">root/
├── .mvn
├── src/
│   ├── main
│   └── <span class="hljs-built_in">test</span>
├── mvnw
├── mvnw.cmd
└── pom.xml
</code></pre>
<h2 id="heading-simple-pom">Simple POM</h2>
<p>The above is what is normally referred to as the <code>Simple POM</code>.</p>
<p><code>modelVersion</code> and <code>Coordinates</code> are the <em>two minimum declarations</em> required for a <code>pom</code> file to work. And it inherits all of the <code>Super POM</code> declarations by default.</p>
<h2 id="heading-super-pom">Super POM</h2>
<p>Maven comes with <code>Super POM</code> as the default POM which defines all the default configurations of a project. As mentioned above, every project POM extends Super POM, and thus, inherits all the configuration.</p>
<p>A sample of Super POM can be found <a target="_blank" href="https://maven.apache.org/ref/3.6.3/maven-model-builder/super-pom.html">here</a>. It contains the following</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">-</span> modelVersion
<span class="hljs-bullet">-</span> repositories
<span class="hljs-bullet">-</span> pluginRepositories
<span class="hljs-bullet">-</span> build
<span class="hljs-bullet">-</span> reporting
<span class="hljs-bullet">-</span> profile
</code></pre>
<h2 id="heading-effective-pom">Effective POM</h2>
<p>This is the final actual POM after merging the values with Super POM.</p>
<p>We can see the final or effective POM by running the command below</p>
<pre><code class="lang-bash">./mvnw <span class="hljs-built_in">help</span>:effective-pom
</code></pre>
<p>The output is pretty long so I will not be attaching the logs here, but if you do run it. You will notice that it is a combination of Super and Simple POM.</p>
<blockquote>
<p>This is useful for debugging when you want to know what exactly forms up your POM, especially in a fairly complex project.</p>
</blockquote>
<h1 id="heading-goal-and-phase">Goal and Phase</h1>
<p>I believe the best place to understand it is through official <a target="_blank" href="https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">Maven Docs</a>. So make sure to run through those. Here, I will add some additional notes that aid me in my understanding.</p>
<h2 id="heading-lifecycle">Lifecycle</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693730273554/7261c0f6-fd7a-4775-8d4e-0358c7797aea.png" alt class="image--center mx-auto" /></p>
<p>This is a bird's eye view of the <code>Maven Lifecycle</code>. To see the complete lifecycle view, refer to the <a target="_blank" href="https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#lifecycle-reference">complete lifecycle</a>.</p>
<h2 id="heading-phase">Phase</h2>
<p>At each lifecycle, it comes with a whole set of the phases that it runs. For example, for <code>clean</code>, it has <code>pre-clean, clean and post-clean</code>.</p>
<p>What's important to note is that <code>build lifecycle</code> needs to run on its own, but <code>default lifecycle</code> should run based on what you want to achieve as it will be (and I quote) "executed in the order given up to the point of the one specified".</p>
<blockquote>
<p>./mvnw [phase]</p>
</blockquote>
<p>For example, if I want to ensure my project can compile, I can either run <code>./mvnw clean compile</code> or <code>./mvnw compile</code>.</p>
<p>Running <code>./mvnw compile</code> will not trigger <code>clean phase</code> unlike running <code>compile</code> which will ensure <code>validate phase</code> is run first.</p>
<pre><code class="lang-bash">./mvnw compile

❌ clean
✔ validate &gt; compile
❌ clean &gt; validate &gt; compile

./mvnw clean compile

✔ clean
✔ validate &gt; compile
❌ clean &gt; validate &gt; compile
</code></pre>
<h3 id="heading-what-happens-in-each-phase">What happens in each phase</h3>
<ul>
<li><p><strong>validate</strong>: validate the project</p>
</li>
<li><p><strong>compile</strong>: compile source code</p>
</li>
<li><p><strong>test</strong>: test the compiled source code</p>
</li>
<li><p><strong>package</strong>: take the compiled source code and package it into JAR</p>
</li>
<li><p><strong>verify</strong>: verify package is valid</p>
</li>
<li><p><strong>install</strong>: install the package into the local repository</p>
</li>
<li><p><strong>deploy</strong>: deploy the package into the remote repository</p>
</li>
</ul>
<h2 id="heading-goal">Goal</h2>
<p>Up to this point, I have only talked about phase. What about <code>goal</code>? It is important to note that for each <code>phase</code>, there will usually be at least one <code>goal</code> (tasks) that is attached which is defined by <code>Maven plugin</code>.</p>
<blockquote>
<p>Refer to <a target="_blank" href="https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#built-in-lifecycle-bindings">goal-binding</a> to know each phase is bound by which goal</p>
</blockquote>
<p>Remember when I mentioned about <code>phase</code> where running one will automatically invoke the previous phases? If you run a particular goal, it will not invoke any previous phase.</p>
<blockquote>
<p>./mvnw [plugin]:[goal]</p>
</blockquote>
<p>What it means is that if I run <code>./mvnw package</code>, it will run the following phase in order</p>
<pre><code class="lang-bash">validate &gt; compile &gt; <span class="hljs-built_in">test</span> &gt; package
</code></pre>
<p>But if I run <code>./mvnw jar:jar</code>, it will execute only the <code>jar</code> goal and not anything before that. So if you don't have necessary resources (i.e./target/classes, etc.), it will throw a warning</p>
<pre><code class="lang-bash">&gt; ./mvnw jar:jar
[INFO] Scanning <span class="hljs-keyword">for</span> projects...
[INFO]
[INFO] -------------------&lt; com.bwgjoseph:maven-101-basic &gt;--------------------
[INFO] Building maven-101-basic 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- jar:3.3.0:jar (default-cli) @ maven-101-basic ---
[WARNING] JAR will be empty - no content was marked <span class="hljs-keyword">for</span> inclusion!
[INFO] Building jar: Z:\Development\workspace\github\bwgjoseph\tutorials\maven-101-basic\target\maven-101-basic-0.0.1-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.682 s
[INFO] Finished at: 2023-09-03T16:05:46+08:00
[INFO] ------------------------------------------------------------------------
</code></pre>
<h1 id="heading-plugin">Plugin</h1>
<p>Maven relies on <code>plugin</code> to perform any type of work. Take a look <a target="_blank" href="https://maven.apache.org/plugins/index.html">here</a> for the list of plugins provided by Maven.</p>
<p>Each plugin provides at least 1 goal to it and has no upper-bound limit (AFAIK).</p>
<p>To understand what goals are available, it is usually described in the various <a target="_blank" href="https://maven.apache.org/plugins/maven-clean-plugin/plugin-info.html">help plugin docs</a>, and <a target="_blank" href="https://maven.apache.org/plugins/maven-compiler-plugin/plugin-info.html">compiler plugin docs</a>.</p>
<p>One could also use the <code>help plugin</code> to list down in the console.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># using groupId with details</span>
./mvnw <span class="hljs-built_in">help</span>:describe -DgroupId=<span class="hljs-string">"org.apache.maven.plugins"</span> -DartifactId=maven-clean-plugin -Ddetail=<span class="hljs-literal">true</span>
<span class="hljs-comment"># using groupId with without details</span>
./mvnw <span class="hljs-built_in">help</span>:describe -DgroupId=<span class="hljs-string">"org.apache.maven.plugins"</span> -DartifactId=maven-clean-plugin
<span class="hljs-comment"># using plugin with version and details</span>
./mvnw <span class="hljs-built_in">help</span>:describe -Dplugin=<span class="hljs-string">"org.apache.maven.plugins:maven-clean-plugin:3.3.1"</span> -Ddetail=<span class="hljs-literal">true</span>
<span class="hljs-comment"># using plugin without version and details</span>
./mvnw <span class="hljs-built_in">help</span>:describe -Dplugin=<span class="hljs-string">"org.apache.maven.plugins:maven-clean-plugin"</span>
</code></pre>
<h2 id="heading-binding-plugin-goal-to-phase">Binding plugin goal to phase</h2>
<p>If you want to bind a plugin goal to a particular phase, you can do it via the <code>execution</code> tag even if the plugin has already bound to some phase.</p>
<p>Let's use <a target="_blank" href="https://github.com/diffplug/spotless/tree/main/plugin-maven#binding-to-maven-phase">spotless-maven</a> as an example.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.diffplug.spotless<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spotless-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${spotless.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- omitted --&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p>As mentioned in the docs, a <code>spotless:check is bound to verify the maven phase</code>, and it means that when running <code>./mvnw verify</code> it will trigger <code>spotless:check</code> goal. If it was not bounded by the plugin, I would have to write something like this</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.diffplug.spotless<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spotless-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${spotless.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- omitted --&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>verify<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>check<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p>And if I want to bound to other phases like <code>compile</code></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.diffplug.spotless<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spotless-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${spotless.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- omitted --&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>spotless-compile-check<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">phase</span>&gt;</span>compile<span class="hljs-tag">&lt;/<span class="hljs-name">phase</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>check<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p>Optionally, I can also give it a unique id which is used to identify (and show) in the console.</p>
<pre><code class="lang-bash">&gt; ./mvnw compile
// omitted
[INFO] --- spotless:2.39.0:check (spotless-compile-check) @ maven-101-basic ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.429 s
[INFO] Finished at: 2023-09-03T16:13:55+08:00
[INFO] ------------------------------------------------------------------------
</code></pre>
<h1 id="heading-dependencies">Dependencies</h1>
<p>One of the most important parts of using build tools like <code>Maven</code> is to allow it to manage the dependencies of the project. Similar to how other build tools such as <code>npm</code> do it as well.</p>
<p>One would specify the dependencies (and version) the project requires, and <code>Maven</code> will download and manage it according to how you defined it.</p>
<p>Below is an example of adding <code>Lombok</code> dependency on the project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.projectlombok<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>lombok<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.18.28<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>provided<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
</code></pre>
<p>There is a lot more to this such as</p>
<ul>
<li><p>classifier</p>
</li>
<li><p>optional</p>
</li>
<li><p>version requirement</p>
</li>
<li><p>exclusion</p>
</li>
</ul>
<p>But I will not be covering those. Refer to <a target="_blank" href="https://maven.apache.org/pom.html#dependencies">here</a> if you are interested to know more. In most cases, all those are not required (including scope), only <code>groupId, artifactId, and version</code> are required.</p>
<h1 id="heading-model-interpolation">Model Interpolation</h1>
<p>Maven provides a way to replace/define value via <code>${...}</code> syntax. Some of the more common ones are</p>
<pre><code class="lang-xml">${project.version}
${project.basedir}
${user.home}
${java.home}
${env.PATH}
</code></pre>
<p>This allows us to define it like this</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.bwgjoseph<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-101-basic<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${project.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
</code></pre>
<h2 id="heading-model-properties">Model Properties</h2>
<p>If I define it under <code>&lt;properties&gt;</code> tag in the <code>pom.xml</code>, I can use it. This is especially useful and commonly used for defining dependency/plugin versions.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>17<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">spotless.version</span>&gt;</span>1.2.3<span class="hljs-tag">&lt;/<span class="hljs-name">spotless.version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.diffplug.spotless<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spotless-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${spotless.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
</code></pre>
<p>When working with <code>Spring Boot</code> project, it is also quite common for us to override the dependency version in <code>&lt;properties&gt;</code> tag like</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>17<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Override dependency version --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">lombok.version</span>&gt;</span>1.18.24<span class="hljs-tag">&lt;<span class="hljs-name">lombok.version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
</code></pre>
<p>Since <code>Lombok</code> dependency is declared and managed via <code>spring-boot-starter-parent</code>, there is no need to re-declare the dependencies in our <code>pom.xml</code> except to declare to the version.</p>
<h1 id="heading-maven-wrapper">Maven Wrapper</h1>
<p>Traditionally, to run <code>mvn</code> command, it is required to download <code>Maven</code> binary, extract, define environment variable, etc. This makes the developer experience less ideal, and more involved.</p>
<blockquote>
<p><code>Maven wrapper</code> was originally a 3rd party project until quite recently that it was officially released as part of <code>Apache Maven Project</code></p>
</blockquote>
<p>Using <code>Maven Wrapper</code> provides an easy way to build any Maven project without having to pre-install <code>Maven</code> on the machine. It has a few key components.</p>
<h2 id="heading-maven-wrapper-jar">Maven Wrapper Jar</h2>
<p><code>Maven Wrapper Jar</code> is responsible for downloading (then installing) of <code>Maven</code> binary, specified in <code>/.mvn/wrapper/maven-wrapper.properties</code> under <code>distributionUrl</code>. And to invoke the targetted maven distribution whenever a command is triggered.</p>
<p>The maven binary will be downloaded, and extracted to <code>%USERPROFILE%/.m2/wrapper/dists</code> (Windows) or <code>~/.m2/wrapper/dists</code> (Linux)</p>
<h2 id="heading-maven-wrapper-distribution">Maven Wrapper Distribution</h2>
<p><code>Maven Wrapper Distribution</code> provides</p>
<ul>
<li><p><code>mvnw</code></p>
</li>
<li><p><code>mvnw.cmd</code></p>
</li>
<li><p><code>.mvn/wrapper/maven-wrapper.properties</code></p>
</li>
</ul>
<p>When invoking <code>mvnw[.cmd]</code>, its job is to trigger/download <code>maven-wrapper</code> depending on the argument passed in. However, the default is to use the wrapper in <code>.mvn/wrapper/maven-wrapper.jar</code> which is why in projects that have these setup, you only run commands like <code>./mvnw clean install</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693673639763/c5ecf9cd-bd4a-47d2-9dd8-f932c94a6676.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-using-maven-wrapper-config">Using Maven Wrapper Config</h2>
<p>If you are using <code>Maven Wrapper</code>, then you can specify and configure the following within <code>.mvn</code> directory</p>
<ul>
<li><p><code>extensions.xml</code></p>
</li>
<li><p><code>maven.config</code></p>
</li>
<li><p><code>jvm.config</code></p>
</li>
</ul>
<p>This means that all these configurations are applicable per project basis. What's interesting is <code>maven.config</code> where you can pass in just about any maven configuration and it will be "injected" to any command you run.</p>
<p>The structure would be such</p>
<pre><code class="lang-bash">root/
├── .mvn/
│   ├── wrapper/
│   │   ├── maven-wrapper.jar
│   │   └── maven-wrapper.properties
│   ├── maven.config
│   ├── settings.xml
│   └── toolchains.xml
└── pom.xml
</code></pre>
<p>If you have custom settings per project, define them within <code>settings.xml</code></p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">settings</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/SETTINGS/1.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">servers</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">server</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>internal-artifactory<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">username</span>&gt;</span>${env.ARTIFACTORY_USER}<span class="hljs-tag">&lt;/<span class="hljs-name">username</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">password</span>&gt;</span>${env.ARTIFACTORY_PASSWORD}<span class="hljs-tag">&lt;/<span class="hljs-name">password</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">server</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">servers</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span>
</code></pre>
<p>And in <code>maven.config</code>, we specify the argument</p>
<pre><code class="lang-xml">--settings="./.mvn/settings.xml"
</code></pre>
<blockquote>
<p>Remember that since Maven 3.9.0, each argument starts in a new line</p>
</blockquote>
<p>So when you run any <code>maven</code> command within the project through the wrapper, it will always append <code>--settings="./.mvn/settings.xml"</code> as part of the command</p>
<h1 id="heading-others">Others</h1>
<h2 id="heading-repositories">Repositories</h2>
<p>Define additional repositories to search for artifacts. The default repository is <a target="_blank" href="https://repo.maven.apache.org/maven2/">repo.maven</a>.</p>
<p>What happens is that when you run any maven command, and it looks for dependency, it will first search locally in <code>%USERPROFILE%\.m2</code> directory. If it cannot find, it will then attempt to locate it remotely via the default repository, or the additional repositories the project defines.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
  ...
  <span class="hljs-tag">&lt;<span class="hljs-name">repositories</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">repository</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">releases</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">enabled</span>&gt;</span>false<span class="hljs-tag">&lt;/<span class="hljs-name">enabled</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">updatePolicy</span>&gt;</span>always<span class="hljs-tag">&lt;/<span class="hljs-name">updatePolicy</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">checksumPolicy</span>&gt;</span>warn<span class="hljs-tag">&lt;/<span class="hljs-name">checksumPolicy</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">releases</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">snapshots</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">enabled</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">enabled</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">updatePolicy</span>&gt;</span>never<span class="hljs-tag">&lt;/<span class="hljs-name">updatePolicy</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">checksumPolicy</span>&gt;</span>fail<span class="hljs-tag">&lt;/<span class="hljs-name">checksumPolicy</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">snapshots</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>Nexus Snapshots<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>snapshots-repo<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">url</span>&gt;</span>https://oss.sonatype.org/content/repositories/snapshots<span class="hljs-tag">&lt;/<span class="hljs-name">url</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">layout</span>&gt;</span>default<span class="hljs-tag">&lt;/<span class="hljs-name">layout</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">repository</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">repositories</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">pluginRepositories</span>&gt;</span>
    ...
  <span class="hljs-tag">&lt;/<span class="hljs-name">pluginRepositories</span>&gt;</span>
  ...
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<blockquote>
<p>Sample pom copied from <a target="_blank" href="https://maven.apache.org/pom.html#repositories">Maven</a></p>
</blockquote>
<p>In most cases, you don't have to specify any, but some organization does have their internal repository hosted using <code>jFrog</code> or <code>Nexus</code> for various reasons.</p>
<h2 id="heading-distribution-management">Distribution Management</h2>
<p>This is where we define where to distribute the project artifact during release when it is deployed.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
  ...
  <span class="hljs-tag">&lt;<span class="hljs-name">distributionManagement</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">repository</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">uniqueVersion</span>&gt;</span>false<span class="hljs-tag">&lt;/<span class="hljs-name">uniqueVersion</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>corp1<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>Corporate Repository<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">url</span>&gt;</span>scp://repo/maven2<span class="hljs-tag">&lt;/<span class="hljs-name">url</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">layout</span>&gt;</span>default<span class="hljs-tag">&lt;/<span class="hljs-name">layout</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">repository</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">snapshotRepository</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">uniqueVersion</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">uniqueVersion</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>propSnap<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>Propellors Snapshots<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">url</span>&gt;</span>sftp://propellers.net/maven<span class="hljs-tag">&lt;/<span class="hljs-name">url</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">layout</span>&gt;</span>legacy<span class="hljs-tag">&lt;/<span class="hljs-name">layout</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">snapshotRepository</span>&gt;</span>
    ...
  <span class="hljs-tag">&lt;/<span class="hljs-name">distributionManagement</span>&gt;</span>
  ...
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>Sample pom copied from <a target="_blank" href="https://maven.apache.org/pom.html#repository">Maven</a></p>
<h2 id="heading-settings">Settings</h2>
<p>In other words, the <code>configuration</code> file for <code>Maven</code>. There are 3 types of settings</p>
<ul>
<li><p>Global: <code>${maven.home}/conf/settings.xml</code></p>
</li>
<li><p>User: <code>${user.home}/.m2/settings.xml</code></p>
</li>
<li><p>Project: <code>${project.basedir}/.mvn/settings.xml</code></p>
</li>
</ul>
<p>The first two (Global and User) are the official and default ones. The last (Project) is what can be done if you are using <code>Maven Wrapper</code> (as mentioned above).</p>
<h2 id="heading-toolchains">Toolchains</h2>
<p>The whole idea of using <code>Toolchains</code> are to allow a project to be built independently from the one Maven is relying on.</p>
<p>It is recommended to keep it in <code>.m2</code> directory but I prefer to place it into <code>.mvn</code> as part of the repository. This way, it removes yet another step for the developer to copy and paste. While I feel that it might be good for the project, but not quite applicable for the general public usage as a whole as every machine configuration pointing to the various JDK paths will be different, and the developer could be working with pointing to a different JDK version in <code>JAVA_HOME</code></p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">toolchains</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- JDK toolchains --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">toolchain</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">type</span>&gt;</span>jdk<span class="hljs-tag">&lt;/<span class="hljs-name">type</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">provides</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>17<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">provides</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">jdkHome</span>&gt;</span>${env.JAVA_HOME}<span class="hljs-tag">&lt;/<span class="hljs-name">jdkHome</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">toolchain</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">toolchains</span>&gt;</span>
</code></pre>
<h2 id="heading-profile">Profile</h2>
<p>Using a profile is a way to pre-define some settings/configuration so it can be activated using <code>-P</code> command</p>
<pre><code class="lang-bash">./mvnw clean package -P default
</code></pre>
<p>Sometimes, the command can get a little bit long, or it is not used frequently, hence, easy to forget the actual syntax. Using <code>Profile</code> might be a good way to overcome this issue.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">profiles</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">profile</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>skip-test<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">skipTests</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">skipTests</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">profile</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">profiles</span>&gt;</span>
</code></pre>
<p>The above defined a Profile with <code>skip-test</code> as the id, and denotes that test should be skipped when running this Profile.</p>
<p>So, rather than running the following</p>
<pre><code class="lang-bash">./mvnw package -DskipTests
</code></pre>
<p>We run the following as a replacement</p>
<pre><code class="lang-bash">./mvnw package -P skip-test
</code></pre>
<p>Granted, this example doesn't showcase the need to have a Profile, but if you have a more complicated setup, this is where it shines, or if you need to run different settings across different environments.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope this is a good enough introduction to <code>Maven</code> and I will follow up with another blog post that covers topics around multi-modules such as the different types of POM (i.e. Aggregate/Parent), using <code>dependencyManagement, pluginManagement</code>.</p>
<p>Personally, my biggest takeaway from this is on <code>Binding plugin goal to Phase</code> where I finally got my "that's how it works" moment as I have always been confused about how it exactly works.</p>
<p>Let me know if any part is confusing!</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/maven-101-basics"><strong>GitHub</strong></a></p>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/2619598/differences-between-dependencymanagement-and-dependencies-in-maven">https://stackoverflow.com/questions/2619598/differences-between-dependencymanagement-and-dependencies-in-maven</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/38723833/what-is-the-purpose-of-mvnw-and-mvnw-cmd-files">https://stackoverflow.com/questions/38723833/what-is-the-purpose-of-mvnw-and-mvnw-cmd-files</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/16205778/what-are-maven-goals-and-phases-and-what-is-their-difference">https://stackoverflow.com/questions/16205778/what-are-maven-goals-and-phases-and-what-is-their-difference</a></p>
</li>
<li><p><a target="_blank" href="https://tomgregory.com/maven-phases-vs-goals/">https://tomgregory.com/maven-phases-vs-goals/</a></p>
</li>
<li><p><a target="_blank" href="https://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html">https://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html</a></p>
</li>
<li><p><a target="_blank" href="https://maven.apache.org/ref/3.9.3/maven-model-builder/#Model_Interpolation">https://maven.apache.org/ref/3.9.3/maven-model-builder/#Model_Interpolation</a></p>
</li>
<li><p><a target="_blank" href="https://maven.apache.org/configure.html">https://maven.apache.org/configure.html</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Spring Security: Configure debug mode programmatically]]></title><description><![CDATA[If you have used Spring Security before, you will likely enable the debug mode at some point Start the application and you will see the following logs What…]]></description><link>https://bwgjoseph.com/spring-security-configure-debug-mode-programmatically</link><guid isPermaLink="true">https://bwgjoseph.com/spring-security-configure-debug-mode-programmatically</guid><category><![CDATA[Springboot]]></category><category><![CDATA[spring security]]></category><category><![CDATA[TIL]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Fri, 14 Jul 2023 15:45:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/WE_Kv_ZB1l0/upload/f7afd7936e05b704e6caf36bdf613364.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>If you have used Spring Security before, you will likely enable the debug mode at some point</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity(debug = true)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfiguration</span> </span>{
    <span class="hljs-comment">// omit</span>
}
</code></pre>
<p>Start the application and you will see the following logs</p>
<pre><code class="lang-plaintext">2023-07-14T23:13:12.247+08:00  INFO 17416 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2822 ms
2023-07-14T23:13:12.546+08:00  WARN 17416 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: e636b35a-35c2-4df8-8404-8a51eb3bfdaa

This generated password is for development use only. Your security configuration must be updated before running your application in production.

2023-07-14T23:13:12.721+08:00  INFO 17416 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@4c6333b3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@7e78bb13, org.springframework.security.web.context.SecurityContextHolderFilter@500ccd39, org.springframework.security.web.header.HeaderWriterFilter@67b36e1e, org.springframework.security.web.csrf.CsrfFilter@547cf6f9, org.springframework.security.web.authentication.logout.LogoutFilter@6af43e35, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@784d6d5e, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@3e7757, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@55145899, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5aed1894, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@49d3c0d7, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@62359ec7, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@22520f84, org.springframework.security.web.access.ExceptionTranslationFilter@394bab9, org.springframework.security.web.access.intercept.AuthorizationFilter@665a6be5]
2023-07-14T23:13:12.754+08:00  WARN 17416 --- [  restartedMain] o.s.s.c.a.web.builders.WebSecurity       : 

********************************************************************
**********        Security debugging is enabled.       *************
**********    This may include sensitive information.  *************
**********      Do not use in a production system!     *************
********************************************************************


2023-07-14T23:13:13.188+08:00  INFO 17416 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
</code></pre>
<p>What if you want to toggle the debug mode programmatically? It will be difficult to do so since it is configured at the annotation level. Is there any other way to configure it? Fortunately, yes! By using <code>WebSecurityCustomizer</code> class</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfiguration</span> </span>{
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> WebSecurityCustomizer <span class="hljs-title">webSecurityCustomizer</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> (web) -&gt; web.debug(<span class="hljs-keyword">true</span>);
    }
}
</code></pre>
<p>That's great. Can it be better, such as toggling it via properties?</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfiguration</span> </span>{
    <span class="hljs-meta">@Value("${web.security.debug}")</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> enableDebug;

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> WebSecurityCustomizer <span class="hljs-title">webSecurityCustomizer</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> (web) -&gt; web.debug(enableDebug);
    }
}
</code></pre>
<p>In <code>application.properties</code>, define the following property</p>
<pre><code class="lang-plaintext">web.security.debug=true
</code></pre>
<p>In production, it can also easily be toggled via the environment variable</p>
<pre><code class="lang-powershell">WEB_SECURITY_DEBUG: false
</code></pre>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>We looked at how to simplify toggling of Spring Security debug mode through property or environment variable.</p>
<p>This is quite useful for me, as it reduces a chunk of logs when not required to see the extra information during runtime.</p>
<h1 id="heading-source-code"><strong>Source Code</strong></h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-security-debug"><strong>GitHub</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Spring Security: Custom Pre-Authentication Flow]]></title><description><![CDATA[In one of my project setups, the authentication process is offloaded to Keycloak and set up with an Open Policy Agent sidecar in a typical Kubernetes…]]></description><link>https://bwgjoseph.com/spring-security-custom-pre-authentication-flow</link><guid isPermaLink="true">https://bwgjoseph.com/spring-security-custom-pre-authentication-flow</guid><category><![CDATA[spring security]]></category><category><![CDATA[Java]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Spring framework]]></category><category><![CDATA[Springboot]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sun, 09 Jul 2023 16:04:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688886427752/49dc1594-4d16-430e-89eb-ce257a61adb8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In one of my project setups, the authentication process is offloaded to Keycloak and set up with an <a target="_blank" href="https://www.openpolicyagent.org/">Open Policy Agent</a> sidecar in a typical Kubernetes deployment. Any request that comes to the service, will be pre-authenticated, and all credentials/information are stored in the headers.</p>
<p>Since I'm using Spring Boot with Spring Security, I wanted to figure out if there's a way to integrate seamlessly within the application through Spring Security without a custom solution (i.e. writing custom filters). After some research, I figured that the most suitable way to do so is via <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/preauth.html#_abstractpreauthenticatedprocessingfilter">Pre-Authentication Scenarios</a> described in the documentation.</p>
<h1 id="heading-goal">Goal</h1>
<p>The goal is to be able to use the header(s) provided, construct and build into an <a target="_blank" href="https://docs.spring.io/spring-security/site/docs/5.8.3/api/org/springframework/security/core/Authentication.html">Authentication</a> object, specifically a <a target="_blank" href="https://docs.spring.io/spring-security/site/docs/5.8.3/api/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationToken.html">PreAuthenticatedAuthenticationToken</a> object, which can then use for all security-related needs.</p>
<p>In this tutorial, I explore how to make use of <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/preauth.html#_request_header_authentication_siteminder">RequestHeaderAuthenticationFilter</a>, an existing implementation provided by Spring Security, that relies on a header to identify and extract the username.</p>
<h1 id="heading-spring-stack">Spring Stack</h1>
<p>At the time of writing, I am using the latest iteration of Spring Boot 2.7.13 with Spring Security 5.8.4 to ensure minimal changes are required when upgrading to Spring Boot 3.x and Spring Security 6.x in the future.</p>
<h1 id="heading-brief-intro-to-spring-security">Brief Intro to Spring Security</h1>
<p>Before I go any further, I want to briefly go through the architecture of Spring Security, specifically in this context.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688883135271/c8fe61fe-e7e2-4395-a728-3413906f83ef.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>When a client sends an HTTP request to the web server</p>
</li>
<li><p>It passes through several Servlet Filters, one of which is <code>DelegatingFilterProxy</code> (created by Spring) to bridge between Servlet Lifecycle and Spring ApplicationContext</p>
</li>
<li><p>Spring Security creates a <code>FilterChainProxy</code> to support <code>SecurityFilterChain</code> where it can have multiple instances of <code>SecurityFilterChain</code></p>
</li>
<li><p>Each of the <code>SecurityFilterChain</code> can have one or more <code>Filter</code> registered, in this case, we are looking specifically at <code>RequestHeaderAuthenticationFilter</code> which extends <code>AbstractPreAuthenticatedProcessingFilter</code></p>
</li>
</ul>
<h1 id="heading-implementation">Implementation</h1>
<p>Although Spring comes with some existing implementation, it doesn't quite fit my use case as I have a custom <code>UserDetails</code> and I need to load my user permission from the database, hence I also need to write my custom <code>AuthenticationUserDetailsService</code> and so on. Fortunately, Spring is super flexible and extensible, hence, I can easily extend and write my implementation as needed.</p>
<p>Without further ado, let's see how to implement this.</p>
<h2 id="heading-initialize-project">Initialize project</h2>
<p>This project is generated from <a target="_blank" href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=2.7.11&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.bwgjoseph&amp;artifactId=spring-security-custom-preauthentication-flow&amp;name=spring-security-custom-preauthentication-flow&amp;description=Spring%20Security%20Custom%20Pre-Authentication%20Flow&amp;packageName=com.bwgjoseph.spring-security-custom-preauthentication-flow&amp;dependencies=devtools,lombok,configuration-processor,web,security">start.spring.io</a></p>
<h2 id="heading-overwrite-spring-security-version">Overwrite Spring Security version</h2>
<p>Spring Boot 2.7.13 comes with Spring Security 5.7.9 by default, so I have to overwrite the version to use Spring Security 5.8.4.</p>
<p>In <code>pom.xml</code>, add the following under <code>properties</code> section</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">spring-security.version</span>&gt;</span>5.8.4<span class="hljs-tag">&lt;/<span class="hljs-name">spring-security.version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
</code></pre>
<h2 id="heading-start-application">Start Application</h2>
<p>This is an extracted portion of the logs when starting the application</p>
<pre><code class="lang-plaintext">2023-07-08 17:05:12.169  WARN 8820 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 70e6538f-cc9f-4764-9959-cd1d2a6cd5b5

This generated password is for development use only. Your security configuration must be updated before running your application in production.

2023-07-08 17:05:12.500  INFO 8820 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@3f690985, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@458bfb19, org.springframework.security.web.context.SecurityContextPersistenceFilter@5e6593, org.springframework.security.web.header.HeaderWriterFilter@1cce17a1, org.springframework.security.web.csrf.CsrfFilter@238de12d, org.springframework.security.web.authentication.logout.LogoutFilter@36d43e9f, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3c373438, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@7fd33069, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@6c864ee5, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5a740d9c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@329f9df5, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@27623b68, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@66e2dd0b, org.springframework.security.web.session.SessionManagementFilter@692b3e18, org.springframework.security.web.access.ExceptionTranslationFilter@13ca9f33, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1cd5e041]
</code></pre>
<p>It's quite difficult to see from the logs what filters are being applied, so let's see it from a different format.</p>
<pre><code class="lang-plaintext">Security filter chain: [
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  UsernamePasswordAuthenticationFilter
  DefaultLoginPageGeneratingFilter
  DefaultLogoutPageGeneratingFilter
  BasicAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]
</code></pre>
<blockquote>
<p>A total of 16 default filters</p>
</blockquote>
<p>Two key things to learn from the log:</p>
<ol>
<li><p>Default Generated Password</p>
</li>
<li><p>Default SecurityFilterChain</p>
</li>
</ol>
<p>Without writing a single line of code, the application is protected by default through a series of sensible defaults (with best practices) provided out of the box by Spring Security. Isn't that awesome?</p>
<blockquote>
<p>Read more of what's happening behind the scene in the <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/getting-started.html#servlet-hello-auto-configuration">documentation</a></p>
</blockquote>
<h2 id="heading-configure-securityfilterchain">Configure SecurityFilterChain</h2>
<p>Create <code>WebSecurityConfig</code> class to define our own <code>SecurityFilterChain</code> and let's disable everything that is not required.</p>
<pre><code class="lang-java"><span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-meta">@Configuration(proxyBeanMethods = false)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfig</span> </span>{

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> http
            .formLogin(AbstractHttpConfigurer::disable)
            .httpBasic(AbstractHttpConfigurer::disable)
            .anonymous(AbstractHttpConfigurer::disable)
            <span class="hljs-comment">// we don't need to enable csrf, as 1) no view, 2) no session cookie authn</span>
            .csrf(AbstractHttpConfigurer::disable)
            <span class="hljs-comment">// disable logout</span>
            .logout(AbstractHttpConfigurer::disable)
            .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
    }
}
</code></pre>
<p>Exclude <code>UserDetailsServiceAutoConfiguration</code> to prevent it from creating a default user and (generated) password via the <code>application.yaml</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">spring:</span>
  <span class="hljs-attr">autoconfigure:</span>
    <span class="hljs-attr">exclude:</span> <span class="hljs-string">org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration</span>
</code></pre>
<p>Run the application again, and the updated <code>SecurityFilterChain</code> looks like this now</p>
<pre><code class="lang-plaintext">Security filter chain: [
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  SessionManagementFilter
  ExceptionTranslationFilter
]
</code></pre>
<blockquote>
<p>Down to 8 filters (50% less!)</p>
</blockquote>
<p>Start the application again, and the log that states the generated password is now gone (disable it via <code>application.yaml</code>).</p>
<h2 id="heading-configure-custom-userdetails">Configure custom UserDetails</h2>
<p>It is very common to have a custom version of <code>UserDetails</code>, and mine is no different.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreAuthUserDetails</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserDetails</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String username;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> List&lt;GrantedAuthority&gt; authorities;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PreAuthUserDetails</span><span class="hljs-params">(String username, Collection&lt;? extends GrantedAuthority&gt; authorities)</span> </span>{
        <span class="hljs-keyword">this</span>.username = username;
        <span class="hljs-keyword">this</span>.authorities = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;(authorities);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-keyword">public</span> Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.authorities;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPassword</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"N/A"</span>;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getUsername</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.username;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isAccountNonExpired</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isAccountNonLocked</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isCredentialsNonExpired</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isEnabled</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }

}
</code></pre>
<h2 id="heading-configure-requestheaderauthenticationfilter">Configure RequestHeaderAuthenticationFilter</h2>
<p>As mentioned, I want to reuse the existing implementation as much as possible and overwrite it <em>only</em> when necessary. So let's create a <code>RequestHeaderAuthenticationFilter</code> bean and configure it.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">()</span> </span>{
    RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
    requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
    requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);

    <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
}
</code></pre>
<p>What <code>RequestHeaderAuthenticationFilter</code> does is extracting the <code>principal</code> from <code>X-User</code> header which will be used in <code>AbstractPreAuthenticatedProcessingFilter#doAuthenticate</code> to create <code>PreAuthenticatedAuthenticationToken</code> object.</p>
<blockquote>
<p>While writing this blog, I realize that RequestHeaderAuthenticationFilter is not registered as part of the Spring Security Filter Chain but as a ServletFilter. So I wrote a separate <a target="_blank" href="https://bwgjoseph.com/why-requestheaderauthenticationfilter-is-not-registered-as-part-of-spring-security-filter-chain">post</a> to explain why</p>
</blockquote>
<p>Start the application now, and the following error will surface</p>
<pre><code class="lang-plaintext">Caused by: java.lang.IllegalArgumentException: An AuthenticationManager must be set
        at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.28.jar:5.3.28]
        at org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter.afterPropertiesSet(AbstractPreAuthenticatedProcessingFilter.java:127) ~[spring-security-web-5.8.4.jar:5.8.4]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.28.jar:5.3.28]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.28.jar:5.3.28]
        ... 56 common frames omitted
</code></pre>
<p>This is because <code>RequestHeaderAuthenticationFilter</code> extends <code>AbstractPreAuthenticatedProcessingFilter</code> which requires an implementation of <code>AuthenticationManager</code> and this brings us to the next point.</p>
<h2 id="heading-register-authenticationmanager">Register AuthenticationManager</h2>
<p>An <code>AuthenticationManager</code> must be provided to perform the <code>authenticate</code> method. But before that, there are two key components (ProviderManager and AuthenticationProvider) we need to understand first.</p>
<blockquote>
<p>AuthenticationManager is the API that defines how Spring Security’s Filters perform authentication.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688809612303/2d723b62-9138-43c0-af87-ca2eee880e0d.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-providermanager">ProviderManager</h3>
<blockquote>
<p>ProviderManager is the most commonly used implementation of AuthenticationManager</p>
</blockquote>
<h3 id="heading-authenticationprovider">AuthenticationProvider</h3>
<blockquote>
<p>Multiple AuthenticationProviders can be injected into ProviderManager. Each AuthenticationProvider performs a specific type of authentication.</p>
</blockquote>
<p>The explanation is taken directly from the documentation <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/architecture.html#servlet-authentication-authenticationmanager">here</a>, <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/architecture.html#servlet-authentication-providermanager">here</a> and <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/architecture.html#servlet-authentication-authenticationprovider">here</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688884303224/4b35b6fc-bd4e-4f12-92d2-2c43e75c23fc.png" alt class="image--center mx-auto" /></p>
<p>In short, for <code>RequestHeaderAuthenticationFilter</code> to perform <code>doAuthenticate</code>. It requires the implementation of <code>AuthenticationManager</code> which outsources the actual authentication through the <code>AuthenticationProvider</code>, which relies on <code>AuthenticationUserDetailsService</code> to create and return the <code>UserDetails</code> object.</p>
<p>Since I am using a custom <code>UserDetails</code> object, I will need to create a custom <code>AuthenticationUserDetailsService</code> to construct our <code>PreAuthUserDetails</code> object.</p>
<blockquote>
<p>There is no need to create custom <code>PreAuthenticatedAuthenticationProvider</code> class since it has all I needed</p>
</blockquote>
<h3 id="heading-configure-authenticationuserdetailsservice">Configure AuthenticationUserDetailsService</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreAuthUserDetailsService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">AuthenticationUserDetailsService</span>&lt;<span class="hljs-title">PreAuthenticatedAuthenticationToken</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> UserDetails <span class="hljs-title">loadUserDetails</span><span class="hljs-params">(PreAuthenticatedAuthenticationToken token)</span> <span class="hljs-keyword">throws</span> UsernameNotFoundException </span>{
        <span class="hljs-comment">// hard-coded authority</span>
        List&lt;GrantedAuthority&gt; authorities = List.of(<span class="hljs-keyword">new</span> SimpleGrantedAuthority(<span class="hljs-string">"ADMIN"</span>));
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.buildUserDetails(token, authorities);
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> UserDetails <span class="hljs-title">buildUserDetails</span><span class="hljs-params">(PreAuthenticatedAuthenticationToken token, Collection&lt;? extends GrantedAuthority&gt; authorities)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> PreAuthUserDetails(token.getName(), authorities);
    }

}
</code></pre>
<p>The nice thing about this is that it doesn't care how the user details object is constructed. It could be loaded from the database, hard-coded, or anything as long it returns the <code>UserDetails</code> object.</p>
<p>For this, I will create a hard-coded authority first. In the later part of the blog, I will explore how to get this from the headers.</p>
<h3 id="heading-update-websecurityconfig">Update WebSecurityConfig</h3>
<p>With all the necessary classes created, and configured. It is time to update the <code>WebSecurityConfig</code> class to reflect the changes I've made thus far.</p>
<pre><code class="lang-java"><span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-meta">@Configuration(proxyBeanMethods = false)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfig</span> </span>{

    <span class="hljs-meta">@Bean</span> <span class="hljs-comment">// 1</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> AuthenticationProvider <span class="hljs-title">authenticationProvider</span><span class="hljs-params">()</span> </span>{
        PreAuthenticatedAuthenticationProvider provider = <span class="hljs-keyword">new</span> PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(<span class="hljs-keyword">new</span> PreAuthUserDetailsService());

        <span class="hljs-keyword">return</span> provider;
    }

    <span class="hljs-meta">@Bean</span> <span class="hljs-comment">// 2</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> AuthenticationManager <span class="hljs-title">authenticationManager</span><span class="hljs-params">(AuthenticationProvider authenticationProvider)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ProviderManager(authenticationProvider);
    }

    <span class="hljs-meta">@Bean</span> <span class="hljs-comment">// 3</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">(AuthenticationManager authenticationManager)</span> </span>{
        RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
        requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
        requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);
        requestHeaderAuthenticationFilter.setAuthenticationManager(authenticationManager);

        <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
    }

    <span class="hljs-meta">@Bean</span> <span class="hljs-comment">// 4</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> http
            .formLogin(AbstractHttpConfigurer::disable)
            .httpBasic(AbstractHttpConfigurer::disable)
            .anonymous(AbstractHttpConfigurer::disable)
            <span class="hljs-comment">// we don't need to enable csrf, as 1) no view, 2) no session cookie authn</span>
            .csrf(AbstractHttpConfigurer::disable)
            <span class="hljs-comment">// disable logout</span>
            .logout(AbstractHttpConfigurer::disable)
            .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
    }
}
</code></pre>
<ol>
<li><p>Register <code>AuthenticationProvider</code> bean and setting <code>PreAuthUserDetailsService</code></p>
</li>
<li><p>Register <code>AuthenticationManager</code> bean</p>
</li>
<li><p>Update <code>RequestHeaderAuthenticationFilter</code> bean to set <code>AuthenticationManager</code></p>
</li>
<li><p>No change</p>
</li>
</ol>
<blockquote>
<p>This is in line with what was drawn in the diagram above on the dependency between each class</p>
</blockquote>
<p>At this stage, I have everything ready and the application should also start up just fine. Next, I will write some tests to verify if this is indeed working as intended.</p>
<h2 id="heading-verification">Verification</h2>
<h3 id="heading-endpoint">Endpoint</h3>
<p>Write a simple endpoint that returns <code>UserDetails</code>.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MeController</span> </span>{

    <span class="hljs-meta">@GetMapping("/me")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> UserDetails <span class="hljs-title">me</span><span class="hljs-params">(<span class="hljs-meta">@AuthenticationPrincipal</span> UserDetails userDetails)</span> </span>{
        <span class="hljs-keyword">return</span> userDetails;
    }
}
</code></pre>
<blockquote>
<p><code>@AuthenticationPrincipal</code> helps to resolve the current authenticated user</p>
</blockquote>
<p>The controller exposes an HTTP GET API endpoint (<code>/me</code>) that returns the authenticated user details.</p>
<h3 id="heading-test-case">Test Case</h3>
<p>Then write a test to verify the interaction.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.http.MediaType;

<span class="hljs-meta">@WebMvcTest(MeController.class)</span>
<span class="hljs-meta">@Import(WebSecurityConfig.class)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MeControllerTests</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MockMvc mockMvc;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">whenCallMe_shouldGetValidResponse2</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">this</span>.mockMvc
            .perform(MockMvcRequestBuilders
                .get(<span class="hljs-string">"/me"</span>)
                .header(<span class="hljs-string">"X-User"</span>, <span class="hljs-string">"joseph"</span>))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.username"</span>).value(<span class="hljs-string">"joseph"</span>))
            .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.authorities"</span>).isArray())
            .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.authorities[0].authority"</span>).value(<span class="hljs-string">"ADMIN"</span>))
            .andDo(MockMvcResultHandlers.print());
    }
}
</code></pre>
<blockquote>
<p>Note that for sliced tests such as <code>@WebMvcTest</code>, we need to import our security configuration since Spring Boot 2.7.x due to the <a target="_blank" href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7-Release-Notes#migrating-from-websecurityconfigureradapter-to-securityfilterchain">deprecated WebSecurityConfigurerAdapter</a>.</p>
<p>To send the request via curl</p>
<pre><code class="lang-bash">curl localhost:8080/me -H <span class="hljs-string">"X-User: joseph"</span>
</code></pre>
</blockquote>
<p>The test does the following</p>
<ul>
<li><p>Configure <code>mockMvc</code> to simulate an HTTP GET request to <code>/me</code> with <code>X-User</code> header</p>
</li>
<li><p>Assert the (JSON) response contains the username and authorities</p>
</li>
<li><p>Print out the log</p>
</li>
</ul>
<p>Here's the log of the request after the test case is ran</p>
<pre><code class="lang-markdown">MockHttpServletRequest:
<span class="hljs-code">      HTTP Method = GET
      Request URI = /me
       Parameters = {}
          Headers = [X-User:"joseph"]
             Body = null
    Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=PreAuthenticatedAuthenticationToken [Principal=PreAuthUserDetails(username=joseph, authorities=[ADMIN]), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[ADMIN]]]}
</span>
Handler:
<span class="hljs-code">             Type = com.bwgjoseph.springsecuritycustompreauthenticationflow.MeController
           Method = com.bwgjoseph.springsecuritycustompreauthenticationflow.MeController#me(UserDetails)
</span>
Async:
<span class="hljs-code">    Async started = false
     Async result = null
</span>
Resolved Exception:
<span class="hljs-code">             Type = null
</span>
ModelAndView:
<span class="hljs-code">        View name = null
             View = null
            Model = null
</span>
FlashMap:
<span class="hljs-code">       Attributes = null
</span>
MockHttpServletResponse:
<span class="hljs-code">           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = application/json
             Body = {"username":"joseph","authorities":[{"authority":"ADMIN"}],"enabled":true,"credentialsNonExpired":true,"accountNonExpired":true,"accountNonLocked":true,"password":"N/A"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []</span>
</code></pre>
<p>It works! Of course, it does, I've spent quite some time writing this blog post, ensuring that it works, so why wouldn't it? 🤣🤣</p>
<h2 id="heading-configure-authenticationdetailssource">Configure AuthenticationDetailsSource</h2>
<p>But.... is that all? Not quite. Remember that I hard-coded the authorities to <code>ADMIN</code> in our existing implementation? Now, how can we get the value from the other header key? Knowing that <code>RequestHeaderAuthenticationFilter</code> supports only getting one header value, which is the username/principal. So how do we extract the additional headers from the request headers, and use it?</p>
<p>For this, I need to create a custom implementation of <code>AuthenticationDetailsSource</code> and <code>WebAuthenticationDetails</code> and pass it to <code>RequestHeaderAuthenticationFilter</code>. Before that, let's try to understand why I need to do so.</p>
<p>If we look at the current implementation of <a target="_blank" href="https://github.com/spring-projects/spring-security/blob/main/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java#L197-L199">AbstractPreAuthenticatedProcessingFilter</a> and zoom into the following code</p>
<pre><code class="lang-java">PreAuthenticatedAuthenticationToken authenticationRequest = <span class="hljs-keyword">new</span> PreAuthenticatedAuthenticationToken(principal, credentials);
authenticationRequest.setDetails(<span class="hljs-keyword">this</span>.authenticationDetailsSource.buildDetails(request));
</code></pre>
<p>We can learn that there is a property - <code>details</code> that we can store any information as long as it is an <code>Object</code> type through <code>AuthenticationDetailsSource</code>. Knowing this, I can then use it to store the additional headers information through the custom implementation of <code>AuthenticationDetailsSource</code> and provide it to <code>RequestHeaderAuthenticationFilter</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreAuthAuthenticationDetailsSource</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">AuthenticationDetailsSource</span>&lt;<span class="hljs-title">HttpServletRequest</span>, <span class="hljs-title">WebAuthenticationDetails</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> WebAuthenticationDetails <span class="hljs-title">buildDetails</span><span class="hljs-params">(HttpServletRequest context)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> PreAuthenticationDetails(context);
    }

}
</code></pre>
<p>The key here is the implementation of <code>PreAuthenticationDetails</code> where it will grab the header from the request.</p>
<pre><code class="lang-java"><span class="hljs-meta">@EqualsAndHashCode(callSuper = true)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreAuthenticationDetails</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebAuthenticationDetails</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">GrantedAuthoritiesContainer</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String HEADER_AUTHORITY = <span class="hljs-string">"X-Authorities"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> List&lt;String&gt; authorities;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PreAuthenticationDetails</span><span class="hljs-params">(HttpServletRequest request)</span> </span>{
        <span class="hljs-keyword">super</span>(request);
        <span class="hljs-keyword">this</span>.authorities = List.of(request.getHeader(HEADER_AUTHORITY).split(<span class="hljs-string">","</span>));
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-keyword">public</span> Collection&lt;? extends GrantedAuthority&gt; getGrantedAuthorities() {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.authorities.stream().map(SimpleGrantedAuthority::<span class="hljs-keyword">new</span>).toList();
    }

}
</code></pre>
<ol>
<li><p>In addition to extending <code>WebAuthenticationDetails</code>, I'm also implementing <code>GrantedAuthoritiesContainer</code> to indicate that this object (<code>PreAuthenticationDetails</code>) can be used to obtain user authorities</p>
</li>
<li><p>I define the header to be of <code>X-Authorities</code> and expect it to be a comma-separated string format</p>
</li>
</ol>
<p>This is just an example of how I can get additional headers value. The number of headers or the format of the headers is entirely dependent on the implementor.</p>
<blockquote>
<p>Ensure that proper validation is done while parsing the header such as checking if the key exists, the value is null, isBlank and so on</p>
</blockquote>
<h3 id="heading-update-preauthuserdetailsservice">Update PreAuthUserDetailsService</h3>
<p>With that, I will be getting the authorities from the <code>PreAuthenticationDetails</code> instead of using the hard-coded values.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreAuthUserDetailsService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">AuthenticationUserDetailsService</span>&lt;<span class="hljs-title">PreAuthenticatedAuthenticationToken</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> UserDetails <span class="hljs-title">loadUserDetails</span><span class="hljs-params">(PreAuthenticatedAuthenticationToken token)</span> <span class="hljs-keyword">throws</span> UsernameNotFoundException </span>{
        <span class="hljs-comment">// update to get the details from token, instead of hardcoded value</span>
        PreAuthenticationDetails details = (PreAuthenticationDetails) token.getDetails();
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.buildUserDetails(token, details.getGrantedAuthorities());
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> UserDetails <span class="hljs-title">buildUserDetails</span><span class="hljs-params">(PreAuthenticatedAuthenticationToken token, Collection&lt;? extends GrantedAuthority&gt; authorities)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> PreAuthUserDetails(token.getName(), authorities);
    }
}
</code></pre>
<h3 id="heading-update-websecurityconfig-1">Update WebSecurityConfig</h3>
<p>Lastly, I need to update the <code>WebSecurityConfig</code> class again to configure <code>RequestHeaderAuthenticationFilter</code> to use my custom <code>AuthenticationDetailsSource</code> class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">(AuthenticationManager authenticationManager)</span> </span>{
    RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
    requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
    requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);
    requestHeaderAuthenticationFilter.setAuthenticationManager(authenticationManager);
    <span class="hljs-comment">// add this line</span>
    requestHeaderAuthenticationFilter.setAuthenticationDetailsSource(<span class="hljs-keyword">new</span> PreAuthAuthenticationDetailsSource());

    <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
}
</code></pre>
<h3 id="heading-update-test-case">Update Test Case</h3>
<p>I also need to update my test case to include the additional header and assertions.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">whenCallMe_shouldGetValidResponse</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">this</span>.mockMvc
        .perform(MockMvcRequestBuilders
            .get(<span class="hljs-string">"/me"</span>)
            .header(<span class="hljs-string">"X-User"</span>, <span class="hljs-string">"joseph"</span>)
            .header(<span class="hljs-string">"X-Authorities"</span>, <span class="hljs-string">"moderator,user"</span>))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.username"</span>).value(<span class="hljs-string">"joseph"</span>))
        .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.authorities"</span>).isArray())
        .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.authorities[0].authority"</span>).value(<span class="hljs-string">"moderator"</span>))
        .andExpect(MockMvcResultMatchers.jsonPath(<span class="hljs-string">"$.authorities[1].authority"</span>).value(<span class="hljs-string">"user"</span>))
        .andDo(MockMvcResultHandlers.print());
}
</code></pre>
<p>The output of the test is as follows</p>
<pre><code class="lang-markdown">MockHttpServletRequest:
<span class="hljs-code">      HTTP Method = GET
      Request URI = /me
       Parameters = {}
          Headers = [X-User:"joseph", X-Authorities:"moderator,user"]
             Body = null
    Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=PreAuthenticatedAuthenticationToken [Principal=PreAuthUserDetails(username=joseph, authorities=[moderator, user]), Credentials=[PROTECTED], Authenticated=true, Details=PreAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[moderator, user]]]}
</span>
Handler:
<span class="hljs-code">             Type = com.bwgjoseph.springsecuritycustompreauthenticationflow.MeController
           Method = com.bwgjoseph.springsecuritycustompreauthenticationflow.MeController#me(UserDetails)
</span>
Async:
<span class="hljs-code">    Async started = false
     Async result = null
</span>
Resolved Exception:
<span class="hljs-code">             Type = null
</span>
ModelAndView:
<span class="hljs-code">        View name = null
             View = null
            Model = null
</span>
FlashMap:
<span class="hljs-code">       Attributes = null
</span>
MockHttpServletResponse:
<span class="hljs-code">           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = application/json
             Body = {"username":"joseph","authorities":[{"authority":"moderator"},{"authority":"user"}],"enabled":true,"password":"N/A","accountNonExpired":true,"credentialsNonExpired":true,"accountNonLocked":true}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []</span>
</code></pre>
<blockquote>
<p>To send the request via curl</p>
<pre><code class="lang-bash">curl localhost:8080/me -H <span class="hljs-string">"X-User: joseph"</span> -H <span class="hljs-string">"X-Authorities: moderator,user"</span>
</code></pre>
</blockquote>
<p>With that, I have everything I needed for the entire implementation.</p>
<h1 id="heading-whats-next">What's next?</h1>
<p>I intend to build and package the implementation into a <code>spring-boot-starter</code> library shortly, and then open-source it internally within my organization so that other projects can benefit from it and use it with zero-configuration.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In summary, we have looked at</p>
<ul>
<li><p>Spring Security Architecture</p>
<ul>
<li>Understanding core components (<code>AuthenticationManager, Filter Chain, ProviderManager, AuthenticationProvider</code>)</li>
</ul>
</li>
<li><p>Configuring <code>SecurityFilterChain</code></p>
</li>
<li><p>Custom implementation of the various classes (<code>PreAuthUserDetailsService, PreAuthAuthenticationDetailsSource, PreAuthenticationDetails</code>) when the default implementation doesn't quite suit our needs</p>
</li>
<li><p>Digging into some of the internal implementations of Spring Security</p>
</li>
<li><p>Wiring up everything together</p>
</li>
</ul>
<p>Documenting the various insights and digging into some of the internal implementations helps me to learn that it is not that difficult to implement it. And finally, allow me to gain more insights into Spring Security Architecture which has been quite elusive to me for the longest time. This should also serve as a note for myself when I start to forget about the details in the future!</p>
<h1 id="heading-source-code"><strong>Source Code</strong></h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-security-custom-preauthentication-flow"><strong>GitHub</strong></a></p>
<h1 id="heading-reference">Reference</h1>
<ul>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/65207826/abstractauthenticationprocessingfilter-triggered-no-matter-what-securityfilterch">https://stackoverflow.com/questions/65207826/abstractauthenticationprocessingfilter-triggered-no-matter-what-securityfilterch</a></p>
</li>
<li><p><a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/architecture.html">https://docs.spring.io/spring-security/reference/5.8/servlet/authentication/architecture.html</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Why RequestHeaderAuthenticationFilter is not registered as part of Spring Security Filter Chain]]></title><description><![CDATA[While I was writing for another blog post, I realize something interesting about RequestHeaderAuthenticationFilter where it isn't registered as part of the…]]></description><link>https://bwgjoseph.com/why-requestheaderauthenticationfilter-is-not-registered-as-part-of-spring-security-filter-chain</link><guid isPermaLink="true">https://bwgjoseph.com/why-requestheaderauthenticationfilter-is-not-registered-as-part-of-spring-security-filter-chain</guid><category><![CDATA[Springboot]]></category><category><![CDATA[spring security]]></category><category><![CDATA[Spring framework]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Wed, 07 Jun 2023 16:01:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686153523465/b86ba263-368e-4e6e-aed3-e79db0236756.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-background">Background</h1>
<p>While I was writing for another blog post, I realize something interesting about <code>RequestHeaderAuthenticationFilter</code> where it isn't registered as part of the <code>SecurityFilterChain</code>. I thought this post should come first, to provide some sort of background knowledge.</p>
<p>Imagine the following configuration</p>
<pre><code class="lang-java"><span class="hljs-meta">@EnableWebSecurity(debug = true)</span>
<span class="hljs-meta">@Configuration(proxyBeanMethods = false)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebSecurityConfig</span> </span>{
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">(AuthenticationManager authenticationManager)</span> </span>{
        RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
        requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
        requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);
        requestHeaderAuthenticationFilter.setAuthenticationManager(authenticationManager);

        <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> http
            .build();
    }

}
</code></pre>
<p>When a request is sent to the server, the following <code>SecurityFilterChain</code> will be logged out</p>
<blockquote>
<p>it is logged because I've set <code>debug = true</code> on <code>@EnableWebSecurity</code></p>
</blockquote>
<pre><code class="lang-plaintext">Security filter chain: [
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
]
</code></pre>
<p>Did you notice what was not inside the <code>SecurityFilterChain</code>?</p>
<p>For me, it wasn't immediately obvious as I was expecting to see <code>RequestHeaderAuthenticationFilter</code> as part of the <code>SecurityFilterChain</code> especially when it is being mentioned in the <a target="_blank" href="https://docs.spring.io/spring-security/reference/5.8/servlet/architecture.html#servlet-security-filters">documentation</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683392888102/e6bd8449-524d-437b-a16e-19af818d0904.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>RequestHeaderAuthenticationFilter is a sub-class of AbstractPreAuthenticatedProcessingFilter</p>
</blockquote>
<h1 id="heading-understanding">Understanding</h1>
<p>So what happens? Why didn't it get registered as part of <code>SecurityFilterChain</code>?</p>
<h2 id="heading-requestheaderauthenticationfilter">RequestHeaderAuthenticationFilter</h2>
<p>To understand that, we need to first look at the implementation of <code>RequestHeaderAuthenticationFilter</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestHeaderAuthenticationFilter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractPreAuthenticatedProcessingFilter</span> </span>{}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AbstractPreAuthenticatedProcessingFilter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">GenericFilterBean</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ApplicationEventPublisherAware</span> </span>{}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericFilterBean</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Filter</span> ... </span>{}
</code></pre>
<p>What the above shows us is that <code>RequestHeaderAuthenticationFilter</code> is essentially a (Servlet) <code>Filter</code>, and the <a target="_blank" href="https://docs.spring.io/spring-boot/docs/2.7.x/reference/htmlsingle/#web.servlet.embedded-container.servlets-filters-listeners.beans">documentation</a> states</p>
<blockquote>
<p>Any <code>Servlet</code>, <code>Filter</code>, or servlet <code>*Listener</code> instance that is a Spring bean is registered with the embedded container.</p>
</blockquote>
<p>This means to say, if we look at the registered filters, we should be able to find <code>RequestHeaderAuthenticationFilter</code>.</p>
<p>Let's do that, and see if that's true by listing down all the registered filters which we can do by turning on the log to <code>debug</code> in <code>application.yaml</code>.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">logging:</span>
  <span class="hljs-attr">level:</span>
    <span class="hljs-attr">org:</span>
      <span class="hljs-attr">springframework:</span>
        <span class="hljs-attr">security:</span> <span class="hljs-string">TRACE</span>
        <span class="hljs-comment"># this will display Mapping filters logs</span>
        <span class="hljs-attr">boot:</span>
          <span class="hljs-attr">web:</span>
            <span class="hljs-attr">servlet:</span>
              <span class="hljs-attr">ServletContextInitializerBeans:</span> <span class="hljs-string">DEBUG</span>
</code></pre>
<h2 id="heading-servlet-filter">Servlet Filter</h2>
<p>When the application is started, the mapping filters will be shown</p>
<pre><code class="lang-powershell"><span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">23</span>:<span class="hljs-number">39</span>:<span class="hljs-number">19.113</span> DEBUG <span class="hljs-number">26544</span> --- [  <span class="hljs-type">restartedMain</span>] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: springSecurityFilterChain urls=[/*] order=<span class="hljs-literal">-100</span>, filterRegistrationBean urls=[/*] order=<span class="hljs-number">2147483647</span>, characterEncodingFilter urls=[/*] order=<span class="hljs-literal">-2147483648</span>, formContentFilter urls=[/*] order=<span class="hljs-literal">-9900</span>, requestContextFilter urls=[/*] order=<span class="hljs-literal">-105</span>, requestHeaderAuthenticationFilter urls=[/*] order=<span class="hljs-number">2147483647</span>
</code></pre>
<p>We can see that it is indeed registered as part of the (Servlet) <code>Filter</code>.</p>
<h2 id="heading-behavior">Behavior</h2>
<p>What does this mean? Should I be concerned? In my own opinion, yes, you should and I will explain why.</p>
<h3 id="heading-default">Default</h3>
<p>First, let's see what's the default behavior by updating the current <code>SecurityFilterChain</code> to the following</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">return</span> http
        <span class="hljs-comment">// added this</span>
        .authorizeHttpRequests(authz -&gt; authz.anyRequest().authenticated())
        .build();
}
</code></pre>
<p>The new line means that any request to the server must come from an authenticated user. Once we update it, restart the application, and make an HTTP request to the server.</p>
<pre><code class="lang-bash">curl localhost:8080
</code></pre>
<p>You will encounter the following exception</p>
<pre><code class="lang-powershell"><span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.515</span>  INFO <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] Spring Security Debugger                 : 

************************************************************

Request received <span class="hljs-keyword">for</span> GET <span class="hljs-string">'/filters'</span>:

org.apache.catalina.connector.RequestFacade@<span class="hljs-number">5085</span>c222

servletPath:/filters
pathInfo:null
headers:
host: localhost:<span class="hljs-number">8080</span>
user<span class="hljs-literal">-agent</span>: <span class="hljs-built_in">curl</span>/<span class="hljs-number">8.0</span>.<span class="hljs-number">1</span>
accept: */*


Security <span class="hljs-keyword">filter</span> chain: [
  <span class="hljs-type">DisableEncodeUrlFilter</span>
  <span class="hljs-type">WebAsyncManagerIntegrationFilter</span>
  <span class="hljs-type">SecurityContextPersistenceFilter</span>
  <span class="hljs-type">HeaderWriterFilter</span>
  <span class="hljs-type">CsrfFilter</span>
  <span class="hljs-type">LogoutFilter</span>
  <span class="hljs-type">RequestCacheAwareFilter</span>
  <span class="hljs-type">SecurityContextHolderAwareRequestFilter</span>
  <span class="hljs-type">AnonymousAuthenticationFilter</span>
  <span class="hljs-type">SessionManagementFilter</span>
  <span class="hljs-type">ExceptionTranslationFilter</span>
  <span class="hljs-type">AuthorizationFilter</span>
]


************************************************************


<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.520</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [<span class="hljs-type">RequestMatcher</span>=<span class="hljs-type">any</span> <span class="hljs-type">request</span>, <span class="hljs-type">Filters</span>=[<span class="hljs-type">org.springframework.security.web.session.DisableEncodeUrlFilter</span>@<span class="hljs-number">50</span><span class="hljs-type">e12d12</span>, <span class="hljs-type">org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter</span>@<span class="hljs-type">c92f53f</span>, <span class="hljs-type">org.springframework.security.web.context.SecurityContextPersistenceFilter</span>@<span class="hljs-number">1</span><span class="hljs-type">f79d63b</span>, <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span>@<span class="hljs-number">30</span><span class="hljs-type">aa5e7d</span>, <span class="hljs-type">org.springframework.security.web.csrf.CsrfFilter</span>@<span class="hljs-number">5534815</span>, <span class="hljs-type">org.springframework.security.web.authentication.logout.LogoutFilter</span>@<span class="hljs-number">2</span><span class="hljs-type">c8c013d</span>, <span class="hljs-type">org.springframework.security.web.savedrequest.RequestCacheAwareFilter</span>@<span class="hljs-number">3</span><span class="hljs-type">e37cacf</span>, <span class="hljs-type">org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter</span>@<span class="hljs-number">2680</span><span class="hljs-type">de6e</span>, <span class="hljs-type">org.springframework.security.web.authentication.AnonymousAuthenticationFilter</span>@<span class="hljs-number">7</span><span class="hljs-type">ed6cc37</span>, <span class="hljs-type">org.springframework.security.web.session.SessionManagementFilter</span>@<span class="hljs-type">df1f38e</span>, <span class="hljs-type">org.springframework.security.web.access.ExceptionTranslationFilter</span>@<span class="hljs-number">48</span><span class="hljs-type">bae627</span>, <span class="hljs-type">org.springframework.security.web.access.intercept.AuthorizationFilter</span>@<span class="hljs-number">54410</span><span class="hljs-type">ddc</span>]] (<span class="hljs-number">1</span>/<span class="hljs-number">1</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.522</span> DEBUG <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Securing GET /filters
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.522</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking DisableEncodeUrlFilter (<span class="hljs-number">1</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.523</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (<span class="hljs-number">2</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.524</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking SecurityContextPersistenceFilter (<span class="hljs-number">3</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.524</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.524</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] w.c.HttpSessionSecurityContextRepository : Created SecurityContextImpl [<span class="hljs-type">Null</span> <span class="hljs-type">authentication</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.527</span> DEBUG <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] s.s.w.c.SecurityContextPersistenceFilter : <span class="hljs-built_in">Set</span> SecurityContextHolder to empty SecurityContext
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.529</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (<span class="hljs-number">4</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.530</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking CsrfFilter (<span class="hljs-number">5</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.531</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.csrf.CsrfFilter         : Did not protect against CSRF since request did not match CsrfNotRequired [<span class="hljs-type">TRACE</span>, <span class="hljs-type">HEAD</span>, <span class="hljs-type">GET</span>, <span class="hljs-type">OPTIONS</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.533</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (<span class="hljs-number">6</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.567</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.s.w.a.logout.LogoutFilter            : Did not match request to Ant [<span class="hljs-type">pattern</span>=<span class="hljs-string">'/logout'</span>, <span class="hljs-type">POST</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.573</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (<span class="hljs-number">7</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.603</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.s.w.s.HttpSessionRequestCache        : No saved request
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.612</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (<span class="hljs-number">8</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.619</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking AnonymousAuthenticationFilter (<span class="hljs-number">9</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.621</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking SessionManagementFilter (<span class="hljs-number">10</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.622</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.s.w.a.AnonymousAuthenticationFilter  : <span class="hljs-built_in">Set</span> SecurityContextHolder to AnonymousAuthenticationToken [<span class="hljs-type">Principal</span>=<span class="hljs-type">anonymousUser</span>, <span class="hljs-type">Credentials</span>=[<span class="hljs-type">PROTECTED</span>], <span class="hljs-type">Authenticated</span>=<span class="hljs-type">true</span>, <span class="hljs-type">Details</span>=<span class="hljs-type">WebAuthenticationDetails</span> [<span class="hljs-type">RemoteIpAddress</span>=<span class="hljs-number">127.0</span><span class="hljs-type">.0.1</span>, <span class="hljs-type">SessionId</span>=<span class="hljs-type">null</span>], <span class="hljs-type">Granted</span> <span class="hljs-type">Authorities</span>=[<span class="hljs-type">ROLE_ANONYMOUS</span>]]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.625</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (<span class="hljs-number">11</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.628</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.security.web.FilterChainProxy        : Invoking AuthorizationFilter (<span class="hljs-number">12</span>/<span class="hljs-number">12</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.630</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span><span class="hljs-variable">$HeaderWriterRequest</span>@<span class="hljs-number">209</span><span class="hljs-type">a3372</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.637</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span><span class="hljs-variable">$HeaderWriterRequest</span>@<span class="hljs-number">209</span><span class="hljs-type">a3372</span>] <span class="hljs-keyword">using</span> org.springframework.security.authorization.AuthenticatedAuthorizationManager@1f83758
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-23</span> <span class="hljs-number">23</span>:<span class="hljs-number">33</span>:<span class="hljs-number">26.653</span> TRACE <span class="hljs-number">20680</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">2</span>] o.s.s.w.a.ExceptionTranslationFilter     : Sending AnonymousAuthenticationToken [<span class="hljs-type">Principal</span>=<span class="hljs-type">anonymousUser</span>, <span class="hljs-type">Credentials</span>=[<span class="hljs-type">PROTECTED</span>], <span class="hljs-type">Authenticated</span>=<span class="hljs-type">true</span>, <span class="hljs-type">Details</span>=<span class="hljs-type">WebAuthenticationDetails</span> [<span class="hljs-type">RemoteIpAddress</span>=<span class="hljs-number">127.0</span><span class="hljs-type">.0.1</span>, <span class="hljs-type">SessionId</span>=<span class="hljs-type">null</span>], <span class="hljs-type">Granted</span> <span class="hljs-type">Authorities</span>=[<span class="hljs-type">ROLE_ANONYMOUS</span>]] to authentication entry point since access is denied

org.springframework.security.access.AccessDeniedException: Access Denied
        at org.springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:<span class="hljs-number">98</span>) ~[<span class="hljs-type">spring</span>-<span class="hljs-type">security</span>-<span class="hljs-type">web</span>-<span class="hljs-number">5.8</span><span class="hljs-type">.3.jar</span>:<span class="hljs-number">5.8</span><span class="hljs-type">.3</span>]
</code></pre>
<blockquote>
<p>I enable TRACE log for org.springframework.security so that it shows all the logs</p>
</blockquote>
<p>But... what about my <code>RequestHeaderAuthenticationFilter</code> that supposed to authenticate my user via <code>X-User</code> header? Why is that not being triggered?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686153116970/a8e9b341-3bb8-4c6a-be04-2d10de7ab360.png" alt class="image--center mx-auto" /></p>
<p>That's because based on the order of the <code>SecurityFilterChain</code>, <code>AnonymousAuthenticationFilter</code> will get processed first and throws <code>Access Denied</code> exception thus it will not reach the servlet <code>Filter</code> which is where <code>RequestHeaderAuthenticationFilter</code> is registered on.</p>
<h3 id="heading-anonymousauthenticationfilter">AnonymousAuthenticationFilter</h3>
<p>What if we disable <code>AnonymousAuthenticationFilter</code>?</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http, AuthenticationManager authenticationManager)</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">return</span> http
        .anonymous(AbstractHttpConfigurer::disable)
        .authorizeHttpRequests(authz -&gt; authz.anyRequest().authenticated())
        .build();
}
</code></pre>
<p>In that case, you will encounter the following</p>
<pre><code class="lang-powershell"><span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.429</span>  INFO <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] Spring Security Debugger                 : 

************************************************************

Request received <span class="hljs-keyword">for</span> GET <span class="hljs-string">'/filters'</span>:

org.apache.catalina.connector.RequestFacade@<span class="hljs-number">21</span>a9c23e

servletPath:/filters
pathInfo:null
headers:
host: localhost:<span class="hljs-number">8080</span>
user<span class="hljs-literal">-agent</span>: <span class="hljs-built_in">curl</span>/<span class="hljs-number">8.0</span>.<span class="hljs-number">1</span>
accept: */*
x<span class="hljs-literal">-user</span>: A


Security <span class="hljs-keyword">filter</span> chain: [
  <span class="hljs-type">DisableEncodeUrlFilter</span>
  <span class="hljs-type">WebAsyncManagerIntegrationFilter</span>
  <span class="hljs-type">SecurityContextPersistenceFilter</span>
  <span class="hljs-type">HeaderWriterFilter</span>
  <span class="hljs-type">CsrfFilter</span>
  <span class="hljs-type">LogoutFilter</span>
  <span class="hljs-type">RequestCacheAwareFilter</span>
  <span class="hljs-type">SecurityContextHolderAwareRequestFilter</span>
  <span class="hljs-type">SessionManagementFilter</span>
  <span class="hljs-type">ExceptionTranslationFilter</span>
  <span class="hljs-type">AuthorizationFilter</span>
]


************************************************************


<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.438</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [<span class="hljs-type">RequestMatcher</span>=<span class="hljs-type">any</span> <span class="hljs-type">request</span>, <span class="hljs-type">Filters</span>=[<span class="hljs-type">org.springframework.security.web.session.DisableEncodeUrlFilter</span>@<span class="hljs-number">7</span><span class="hljs-type">f18dabf</span>, <span class="hljs-type">org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter</span>@<span class="hljs-number">593</span><span class="hljs-type">ea2b2</span>, <span class="hljs-type">org.springframework.security.web.context.SecurityContextPersistenceFilter</span>@<span class="hljs-number">78115</span><span class="hljs-type">e1b</span>, <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span>@<span class="hljs-number">6</span><span class="hljs-type">cfa908e</span>, <span class="hljs-type">org.springframework.security.web.csrf.CsrfFilter</span>@<span class="hljs-number">59929929</span>, <span class="hljs-type">org.springframework.security.web.authentication.logout.LogoutFilter</span>@<span class="hljs-number">58</span><span class="hljs-type">be5f1e</span>, <span class="hljs-type">org.springframework.security.web.savedrequest.RequestCacheAwareFilter</span>@<span class="hljs-number">3</span><span class="hljs-type">d9ed909</span>, <span class="hljs-type">org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter</span>@<span class="hljs-number">62</span><span class="hljs-type">d540a8</span>, <span class="hljs-type">org.springframework.security.web.session.SessionManagementFilter</span>@<span class="hljs-number">7</span><span class="hljs-type">db987f9</span>, <span class="hljs-type">org.springframework.security.web.access.ExceptionTranslationFilter</span>@<span class="hljs-number">75</span><span class="hljs-type">c8948d</span>, <span class="hljs-type">org.springframework.security.web.access.intercept.AuthorizationFilter</span>@<span class="hljs-number">43</span><span class="hljs-type">fcbf99</span>]] (<span class="hljs-number">1</span>/<span class="hljs-number">1</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.442</span> DEBUG <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Securing GET /filters
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.448</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking DisableEncodeUrlFilter (<span class="hljs-number">1</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.456</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (<span class="hljs-number">2</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.460</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking SecurityContextPersistenceFilter (<span class="hljs-number">3</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.464</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.467</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] w.c.HttpSessionSecurityContextRepository : Created SecurityContextImpl [<span class="hljs-type">Null</span> <span class="hljs-type">authentication</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.467</span> DEBUG <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] s.s.w.c.SecurityContextPersistenceFilter : <span class="hljs-built_in">Set</span> SecurityContextHolder to empty SecurityContext
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.468</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (<span class="hljs-number">4</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.469</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking CsrfFilter (<span class="hljs-number">5</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.470</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.csrf.CsrfFilter         : Did not protect against CSRF since request did not match CsrfNotRequired [<span class="hljs-type">TRACE</span>, <span class="hljs-type">HEAD</span>, <span class="hljs-type">GET</span>, <span class="hljs-type">OPTIONS</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.472</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (<span class="hljs-number">6</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.473</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.s.w.a.logout.LogoutFilter            : Did not match request to Ant [<span class="hljs-type">pattern</span>=<span class="hljs-string">'/logout'</span>, <span class="hljs-type">POST</span>]       
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.475</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (<span class="hljs-number">7</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.478</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.s.w.s.HttpSessionRequestCache        : No saved request
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.479</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (<span class="hljs-number">8</span>/<span class="hljs-number">11</span>)      
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.480</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking SessionManagementFilter (<span class="hljs-number">9</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.482</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (<span class="hljs-number">10</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.483</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.security.web.FilterChainProxy        : Invoking AuthorizationFilter (<span class="hljs-number">11</span>/<span class="hljs-number">11</span>)
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.484</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span><span class="hljs-variable">$HeaderWriterRequest</span>@<span class="hljs-number">3</span><span class="hljs-type">e406d3a</span>]
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.485</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ <span class="hljs-type">org.springframework.security.web.header.HeaderWriterFilter</span><span class="hljs-variable">$HeaderWriterRequest</span>@<span class="hljs-number">3</span><span class="hljs-type">e406d3a</span>] <span class="hljs-keyword">using</span> org.springframework.security.authorization.AuthenticatedAuthorizationManager@13bd82ef
<span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">22</span>:<span class="hljs-number">10</span>:<span class="hljs-number">48.488</span> TRACE <span class="hljs-number">29080</span> --- [<span class="hljs-type">nio</span>-<span class="hljs-number">8080</span>-<span class="hljs-type">exec</span>-<span class="hljs-number">1</span>] o.s.s.w.a.ExceptionTranslationFilter     : Sending to authentication entry point since authentication failed

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found <span class="hljs-keyword">in</span> the SecurityContext
        at org.springframework.security.web.access.intercept.AuthorizationFilter.getAuthentication(AuthorizationFilter.java:<span class="hljs-number">143</span>) ~[<span class="hljs-type">spring</span>-<span class="hljs-type">security</span>-<span class="hljs-type">web</span>-<span class="hljs-number">5.8</span><span class="hljs-type">.3.jar</span>:<span class="hljs-number">5.8</span><span class="hljs-type">.3</span>]
        at org.springframework.security.authorization.AuthenticatedAuthorizationManager.check(AuthenticatedAuthorizationManager.java:<span class="hljs-number">115</span>) ~[<span class="hljs-type">spring</span>-<span class="hljs-type">security</span>-<span class="hljs-type">core</span>-<span class="hljs-number">5.8</span><span class="hljs-type">.3.jar</span>:<span class="hljs-number">5.8</span><span class="hljs-type">.3</span>]
    // omitted
</code></pre>
<p>Let's zoom in on this particular message - <code>An Authentication object was not found in the SecurityContext</code>. This means there is no chance for <code>Authentication</code> to happen and <code>SecurityContext</code> was not constructed, since no Filter is handling it.</p>
<p>In short, you need to ensure that the <code>Authentication</code> filter is registered as part of the <code>SecurityFilterChain</code>. If that is the case, what can we do to ensure that?</p>
<h1 id="heading-solution">Solution</h1>
<h2 id="heading-do-not-register-as-bean">Do not register as <code>@Bean</code></h2>
<p>Simply remove <code>@Bean</code> annotation on <code>RequestHeaderAuthenticationFilter</code> and register it as part of <code>SecurityFilterChain</code> manually</p>
<pre><code class="lang-java"><span class="hljs-comment">// removed @Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">(AuthenticationManager authenticationManager)</span> </span>{
    RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
    requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
    requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);
    requestHeaderAuthenticationFilter.setAuthenticationManager(authenticationManager);

    <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
}

<span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">securityFilterChain</span><span class="hljs-params">(HttpSecurity http, AuthenticationManager authenticationManager)</span> <span class="hljs-keyword">throws</span> Exception </span>{
    <span class="hljs-keyword">return</span> http
        .anonymous(AbstractHttpConfigurer::disable)
        .authorizeHttpRequests(authz -&gt; authz.anyRequest().authenticated())
        <span class="hljs-comment">// register the filter manually</span>
        .addFilter(requestHeaderAuthenticationFilter(authenticationManager))
        .build();
}
</code></pre>
<p>Now, in the <code>SecurityFilterChain</code>, we can see the following</p>
<pre><code class="lang-powershell">Security <span class="hljs-keyword">filter</span> chain: [
  <span class="hljs-type">DisableEncodeUrlFilter</span>
  <span class="hljs-type">WebAsyncManagerIntegrationFilter</span>
  <span class="hljs-type">SecurityContextPersistenceFilter</span>
  <span class="hljs-type">HeaderWriterFilter</span>
  <span class="hljs-type">CsrfFilter</span>
  <span class="hljs-type">LogoutFilter</span>
  <span class="hljs-type">RequestHeaderAuthenticationFilter</span> &lt;&lt; <span class="hljs-type">look</span> <span class="hljs-type">at</span> <span class="hljs-type">this</span>
  <span class="hljs-type">RequestCacheAwareFilter</span>
  <span class="hljs-type">SecurityContextHolderAwareRequestFilter</span>
  <span class="hljs-type">AnonymousAuthenticationFilter</span>
  <span class="hljs-type">SessionManagementFilter</span>
  <span class="hljs-type">ExceptionTranslationFilter</span>
  <span class="hljs-type">AuthorizationFilter</span>
]
</code></pre>
<p>Notice that <code>RequestHeaderAuthenticationFilter</code> is now part of the <code>SecurityFilterChain</code> and no longer exist as part of the servlet <code>Filter</code>?</p>
<pre><code class="lang-powershell"><span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">23</span>:<span class="hljs-number">45</span>:<span class="hljs-number">05.014</span> DEBUG <span class="hljs-number">26544</span> --- [  <span class="hljs-type">restartedMain</span>] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: springSecurityFilterChain urls=[/*] order=<span class="hljs-literal">-100</span>, filterRegistrationBean urls=[/*] order=<span class="hljs-number">2147483647</span>, filterRegistrationBean urls=[/*] order=<span class="hljs-number">2147483647</span>, characterEncodingFilter urls=[/*] order=<span class="hljs-literal">-2147483648</span>, formContentFilter urls=[/*] order=<span class="hljs-literal">-9900</span>, requestContextFilter urls=[/*] order=<span class="hljs-literal">-105</span>
</code></pre>
<p>Now, if you make an HTTP request to the server, you will encounter the following error</p>
<pre><code class="lang-bash">curl localhost:8080
</code></pre>
<pre><code class="lang-java"><span class="hljs-number">2023</span>-<span class="hljs-number">05</span>-<span class="hljs-number">23</span> <span class="hljs-number">23</span>:<span class="hljs-number">45</span>:<span class="hljs-number">53.779</span> ERROR <span class="hljs-number">14644</span> --- [nio-<span class="hljs-number">8080</span>-exec-<span class="hljs-number">2</span>] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() <span class="hljs-keyword">for</span> servlet [dispatcherServlet] in context with path [] threw exception

org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException: X-User header not found in request.
        at org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter.getPreAuthenticatedPrincipal(RequestHeaderAuthenticationFilter.java:<span class="hljs-number">64</span>) ~[spring-security-web-<span class="hljs-number">5.8</span>.<span class="hljs-number">3.</span>jar:<span class="hljs-number">5.8</span>.<span class="hljs-number">3</span>]
        at org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter.doAuthenticate(AbstractPreAuthenticatedProcessingFilter.java:<span class="hljs-number">189</span>) ~[spring-security-web-<span class="hljs-number">5.8</span>.<span class="hljs-number">3.</span>jar:<span class="hljs-number">5.8</span>.<span class="hljs-number">3</span>]
    <span class="hljs-comment">// omitted</span>
</code></pre>
<p>We can see that <code>RequestHeaderAuthenticationFilter</code> is being triggered, and that it requires <code>X-User</code> header now, as per what we have configured.</p>
<h2 id="heading-configure-filterregistrationbean">Configure FilterRegistrationBean</h2>
<p>What if I must register <code>RequestHeaderAuthenticationFilter</code> as a <code>@Bean</code> and I want to exclude it from registering with the <code>Servlet Filter</code>?</p>
<p>You can declare a <code>FilterRegistrationBean</code> and set it to <code>false</code></p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> RequestHeaderAuthenticationFilter <span class="hljs-title">requestHeaderAuthenticationFilter</span><span class="hljs-params">(AuthenticationManager authenticationManager)</span> </span>{
    RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter = <span class="hljs-keyword">new</span> RequestHeaderAuthenticationFilter();
    requestHeaderAuthenticationFilter.setPrincipalRequestHeader(<span class="hljs-string">"X-User"</span>);
    requestHeaderAuthenticationFilter.setExceptionIfHeaderMissing(<span class="hljs-keyword">true</span>);
    requestHeaderAuthenticationFilter.setAuthenticationManager(authenticationManager);

    <span class="hljs-keyword">return</span> requestHeaderAuthenticationFilter;
}

<span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> FilterRegistrationBean&lt;RequestHeaderAuthenticationFilter&gt; <span class="hljs-title">registration</span><span class="hljs-params">(RequestHeaderAuthenticationFilter filter)</span> </span>{
    FilterRegistrationBean&lt;RequestHeaderAuthenticationFilter&gt; registration = <span class="hljs-keyword">new</span> FilterRegistrationBean&lt;&gt;(filter);
    registration.setEnabled(<span class="hljs-keyword">false</span>);
    <span class="hljs-keyword">return</span> registration;
}
</code></pre>
<p>When the application start-up, it will show that <code>RequestHeaderAuthenticationFilter</code> is not being registered. Similar to what we have, when we don't register <code>RequestHeaderAuthenticationFilter</code> as a <code>@Bean</code>.</p>
<pre><code class="lang-powershell"><span class="hljs-number">2023</span><span class="hljs-literal">-05</span><span class="hljs-literal">-25</span> <span class="hljs-number">23</span>:<span class="hljs-number">45</span>:<span class="hljs-number">05.014</span> DEBUG <span class="hljs-number">26544</span> --- [  <span class="hljs-type">restartedMain</span>] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: springSecurityFilterChain urls=[/*] order=<span class="hljs-literal">-100</span>, filterRegistrationBean urls=[/*] order=<span class="hljs-number">2147483647</span>, filterRegistrationBean urls=[/*] order=<span class="hljs-number">2147483647</span>, characterEncodingFilter urls=[/*] order=<span class="hljs-literal">-2147483648</span>, formContentFilter urls=[/*] order=<span class="hljs-literal">-9900</span>, requestContextFilter urls=[/*] order=<span class="hljs-literal">-105</span>
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>We looked at why a Filter - <code>RequestHeaderAuthenticationFilter</code> - is not automatically registered as part of <code>SecurityFilterChain</code>. And moved on to see how we can register it manually, and how to disable the automatic registration of Filter in <code>Servlet</code> via <code>FilterRegistrationBean</code>.</p>
<p>Knowing that <code>Spring Boot</code> automatically registers any <code>Servlet</code>, <code>Filter</code>, or servlet <code>*Listener</code> instance that is a Spring bean with the embedded container is important because sometimes you may encounter an issue where your Filter gets invoked twice.</p>
<h1 id="heading-source-code"><strong>Source Code</strong></h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-security-filter-chain"><strong>GitHub</strong></a><strong>.</strong></p>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/39314176/filter-invoke-twice-when-register-as-spring-bean">https://stackoverflow.com/questions/39314176/filter-invoke-twice-when-register-as-spring-bean</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/28421966/prevent-spring-boot-from-registering-a-servlet-filter">https://stackoverflow.com/questions/28421966/prevent-spring-boot-from-registering-a-servlet-filter</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/spring-projects/spring-boot/issues/31142">https://github.com/spring-projects/spring-boot/issues/31142</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/spring-projects/spring-boot/issues/31511">https://github.com/spring-projects/spring-boot/issues/31511</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Spring Boot Debezium (embedded) Engine with MongoDB as Source - Part 1]]></title><description><![CDATA[I am exploring to use Debezium as my Change Data Capture tool to introduce it into my team/project. I wanted to keep it simple, hence I chose to go with…]]></description><link>https://bwgjoseph.com/spring-boot-debezium-embedded-engine-with-mongodb-as-source-part-1</link><guid isPermaLink="true">https://bwgjoseph.com/spring-boot-debezium-embedded-engine-with-mongodb-as-source-part-1</guid><category><![CDATA[debezium]]></category><category><![CDATA[cdc]]></category><category><![CDATA[change data capture]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sun, 12 Mar 2023 07:50:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678606880430/e7c955e0-76aa-4a8f-94b8-5364ba46d9a3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I am exploring to use <code>Debezium</code> as my <code>Change Data Capture</code> tool to introduce it into my team/project. I wanted to keep it simple, hence I chose to go with the embedded engine.</p>
<p>I wasn't able to find many examples of using <code>MongoDB</code> as a source database (especially not with the embedded one). As a result, I needed to scout through the various documentation and blogs to figure out how to configure <code>Spring Boot with Debezium (embedded) Engine</code> plus connecting to <code>MongoDB</code> as the source, and <code>Elasticsearch</code> as the destination.</p>
<p>Furthermore, I hope this will serve as a guide to others who face the same issue as me.</p>
<h1 id="heading-end-goal">End Goal</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678560286319/250ee6e4-7388-4edb-aa5f-fe1c88ff3f48.png" alt class="image--center mx-auto" /></p>
<p>What I wanted to achieve is pretty straightforward</p>
<ul>
<li><p>host an embedded <code>Debezium</code> on top of <code>spring-boot</code></p>
</li>
<li><p>connect to mongo instance (with replicas) through <code>debezium-connector-mongodb</code></p>
</li>
<li><p>subscribe to the change events (<code>RecordChangeEvent</code>)</p>
</li>
<li><p>index into <code>Elasticsearch</code></p>
</li>
</ul>
<h1 id="heading-setup-project">Setup Project</h1>
<h2 id="heading-prerequisite">Prerequisite</h2>
<ul>
<li><p>MongoDB Server</p>
<ul>
<li>Local or Cloud but requires having <a target="_blank" href="https://debezium.io/documentation/reference/2.1/connectors/mongodb.html#supported-mongodb-topologies">replica set</a></li>
</ul>
</li>
<li><p>Elasticsearch Server</p>
<ul>
<li>Local or Cloud</li>
</ul>
</li>
</ul>
<p>I have trouble configuring <code>MongoDB</code> with a replica set for local setup, I will be using a free instance from <code>MongoDB Atlas</code>. However, for <code>Elasticsearch</code> is straightforward to configure a local instance. I spin it up via the <a target="_blank" href="https://github.com/bwgjoseph/spring-boot-debezium-mongodb-es/blob/main/docker-compose.yml"><strong>docker-compose</strong></a> script.</p>
<p>It is a bumper that <code>MongoDB Atlas</code> is offering only version 5.x for free instance, and not the latest and greatest version as a <a target="_blank" href="https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/">default</a>. This means that I am not able to fully test it with the <a target="_blank" href="https://www.mongodb.com/docs/manual/changeStreams/#change-streams-with-document-pre--and-post-images">Change Streams with Document Pre- and Post-Images</a> feature that is only available on version 6 onwards.</p>
<h2 id="heading-initialize-a-spring-boot-project">Initialize a spring boot project</h2>
<p>Go to <a target="_blank" href="https://start.spring.io">start.spring.io</a> and generate your spring boot project. Otherwise, click on <a target="_blank" href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=2.7.9&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.bwgjoseph&amp;artifactId=spring-boot-debezium-mongodb-es&amp;name=spring-boot-debezium-mongodb-es&amp;description=Spring%20Boot%20Debezium%20MongoDB%20Elasticsearch&amp;packageName=com.bwgjoseph.spring-boot-debezium-mongodb-es&amp;dependencies=devtools,lombok,configuration-processor,web,data-mongodb">this link</a> for the preset that I've configured.</p>
<p>While it is not necessary to bring in <code>spring-boot-starter-web</code>, it is an easy way to bring in the necessary dependencies. We don't need it to run as a <code>web application</code>, so we can turn it off by adding the configuration below</p>
<pre><code class="lang-yaml"><span class="hljs-attr">spring:</span>
  <span class="hljs-attr">main:</span>
    <span class="hljs-attr">web-application-type:</span> <span class="hljs-string">none</span>
</code></pre>
<p>Note that at the time of writing, while <code>Spring Boot 3.x</code> is available, I am still using <code>Spring Boot 2.7.9</code> for my setup.</p>
<h2 id="heading-add-debezium-dependencies">Add Debezium dependencies</h2>
<p>Following the documentation stated in <a target="_blank" href="https://debezium.io/documentation/reference/2.1/development/engine.html#_dependencies">Debezium</a>, we need to add the following dependencies.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.debezium<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>debezium-api<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${version.debezium}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.debezium<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>debezium-embedded<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${version.debezium}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<blockquote>
<p>At the time of writing, I am using <code>2.1.2.Final</code> for Debezium</p>
</blockquote>
<p>As I am connecting to <code>MongoDB</code> as my source, I needed to add the connector dependency as well.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.debezium<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>debezium-connector-mongodb<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${version.debezium}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<h3 id="heading-override-mongo-version">Override Mongo Version</h3>
<p>If you are also using <code>spring-boot 2.7.x</code>, then make sure you override the <code>mongo-driver version</code> to at least <code>4.7.1</code> which <code>Debezium 2.1.2-Final</code> is depending on. To override, simply add <code>mongodb.version</code> under <code>properties</code> section in <code>pom.xml</code></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-comment">&lt;!--
        Spring Boot 2.7.9 brings in mongo 4.6.1 but debezium relies on 4.7.1
        Manually define to prevent debezium from using 4.6.1
    --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">mongodb.version</span>&gt;</span>4.7.1<span class="hljs-tag">&lt;/<span class="hljs-name">mongodb.version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">debezium.version</span>&gt;</span>2.1.2.Final<span class="hljs-tag">&lt;/<span class="hljs-name">debezium.version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
</code></pre>
<p>Initially, I thought there was a <a target="_blank" href="https://issues.redhat.com/browse/DBZ-6181">bug</a> on <code>Debezium</code> but didn't realize that it was being overwritten. Don't make the same rookie mistake as me.</p>
<h2 id="heading-debezium-configuration">Debezium Configuration</h2>
<p>As per my understanding, there are two types of property; <a target="_blank" href="https://debezium.io/documentation/reference/2.1/connectors/mongodb.html#supported-mongodb-topologies">Engine</a> and <a target="_blank" href="https://debezium.io/documentation/reference/2.1/connectors/mongodb.html#mongodb-connector-properties">Connector</a>.</p>
<h3 id="heading-engine">Engine</h3>
<p>These properties are required to be set up no matter which connector you choose to use with <code>Debezium</code>.</p>
<h3 id="heading-connector">Connector</h3>
<p>These properties are specific to the database you are connecting to, so do refer to the respective documentation on what is required to set.</p>
<p>There is a huge list of properties that can be set, but I am only configuring the minimal to get it to work. Several defaults are quite sensible, and you don't have to overwrite if you don't have to.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.io.File;
<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;
<span class="hljs-keyword">import</span> io.debezium.config.Configuration;

<span class="hljs-meta">@org</span>.springframework.context.annotation.Configuration
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DebeziumConnectorConfig</span> </span>{
    <span class="hljs-comment">// based off https://debezium.io/documentation/reference/2.1/connectors/mongodb.html#mongodb-connector-properties</span>
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Configuration <span class="hljs-title">mongodbConnector</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>{
        File offsetStorageTempFile = File.createTempFile(<span class="hljs-string">"offsets_"</span>, <span class="hljs-string">".dat"</span>);

        <span class="hljs-keyword">return</span> Configuration.create()
                <span class="hljs-comment">// engine properties</span>
                .with(<span class="hljs-string">"name"</span>, <span class="hljs-string">"sbd-mongodb"</span>)
                .with(<span class="hljs-string">"connector.class"</span>, <span class="hljs-string">"io.debezium.connector.mongodb.MongoDbConnector"</span>)
                .with(<span class="hljs-string">"offset.storage"</span>, <span class="hljs-string">"org.apache.kafka.connect.storage.FileOffsetBackingStore"</span>)
                .with(<span class="hljs-string">"offset.storage.file.filename"</span>, offsetStorageTempFile.getAbsolutePath())
                .with(<span class="hljs-string">"offset.flush.interval.ms"</span>, <span class="hljs-string">"60000"</span>)
                <span class="hljs-comment">// connector specific properties</span>
                .with(<span class="hljs-string">"mongodb.connection.string"</span>, <span class="hljs-string">"mongodb+srv://sb-debezium.1ewsyzd.mongodb.net"</span>)
                .with(<span class="hljs-string">"topic.prefix"</span>, <span class="hljs-string">"sbd-mongodb-connector"</span>)
                .with(<span class="hljs-string">"mongodb.user"</span>, <span class="hljs-string">"bwgjoseph"</span>)
                .with(<span class="hljs-string">"mongodb.password"</span>, <span class="hljs-string">"&lt;redacted&gt;"</span>)
                .with(<span class="hljs-string">"mongodb.ssl.enabled"</span>, <span class="hljs-string">"true"</span>) <span class="hljs-comment">// default false</span>
                .with(<span class="hljs-string">"database.include.list"</span>, <span class="hljs-string">"source"</span>) <span class="hljs-comment">// default empty</span>
                .with(<span class="hljs-string">"snapshot.delay.ms"</span>, <span class="hljs-string">"100"</span>)
                .with(<span class="hljs-string">"errors.log.include.messages"</span>, <span class="hljs-string">"true"</span>)
                .build();
    }
}
</code></pre>
<p>A few points to note:</p>
<ul>
<li><p><code>name</code> has to be unique across the connectors</p>
</li>
<li><p><code>mongodb.hosts</code> is not required if <code>mongodb.connection.string</code> is configured</p>
</li>
<li><p><code>offset.storage</code> is necessary to persist offset, for this purpose, it is alright to be created in a temporary folder, but it should be created and stored in a persistent volume</p>
</li>
<li><p><code>mongodb.ssl.enabled</code> must be set to <code>true</code> if connecting to <code>MongoDB Atlas</code></p>
</li>
</ul>
<h2 id="heading-setup-debezium-service">Setup Debezium Service</h2>
<p>Now that we have everything set up, it is time to configure the actual service to start and listen for changes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.concurrent.Executor;
<span class="hljs-keyword">import</span> java.util.concurrent.Executors;

<span class="hljs-keyword">import</span> javax.annotation.PostConstruct;
<span class="hljs-keyword">import</span> javax.annotation.PreDestroy;

<span class="hljs-keyword">import</span> org.apache.kafka.connect.data.Struct;
<span class="hljs-keyword">import</span> org.apache.kafka.connect.source.SourceRecord;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Service;

<span class="hljs-keyword">import</span> io.debezium.config.Configuration;
<span class="hljs-keyword">import</span> io.debezium.embedded.Connect;
<span class="hljs-keyword">import</span> io.debezium.engine.DebeziumEngine;
<span class="hljs-keyword">import</span> io.debezium.engine.RecordChangeEvent;
<span class="hljs-keyword">import</span> io.debezium.engine.format.ChangeEventFormat;
<span class="hljs-keyword">import</span> lombok.extern.slf4j.Slf4j;

<span class="hljs-meta">@Slf4j</span>
<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DebeziumSourceEventListener</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Executor executor;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> DebeziumEngine&lt;RecordChangeEvent&lt;SourceRecord&gt;&gt; debeziumEngine;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DebeziumSourceEventListener</span><span class="hljs-params">(Configuration mongodbConnector)</span> </span>{
        <span class="hljs-keyword">this</span>.executor = Executors.newSingleThreadExecutor();
        <span class="hljs-keyword">this</span>.debeziumEngine = DebeziumEngine.create(ChangeEventFormat.of(Connect.class))
            .using(mongodbConnector.asProperties())
            .notifying(<span class="hljs-keyword">this</span>::handleChangeEvent)
            .build();
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleChangeEvent</span><span class="hljs-params">(RecordChangeEvent&lt;SourceRecord&gt; sourceRecordRecordChangeEvent)</span> </span>{
        SourceRecord sourceRecord = sourceRecordRecordChangeEvent.record();
        Struct sourceRecordKey = (Struct) sourceRecord.key();
        Struct sourceRecordValue = (Struct) sourceRecord.value();

        log.info(<span class="hljs-string">"Key = '"</span> + sourceRecordKey + <span class="hljs-string">"' value = '"</span> + sourceRecordValue + <span class="hljs-string">"'"</span>);
    }

    <span class="hljs-meta">@PostConstruct</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">this</span>.executor.execute(debeziumEngine);
    }

    <span class="hljs-meta">@PreDestroy</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">stop</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.debeziumEngine != <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">this</span>.debeziumEngine.close();
        }
    }
}
</code></pre>
<h1 id="heading-a-quick-demo">A quick demo</h1>
<p>Let's imagine you have another service (endpoint) that creates a <code>Person</code> and save into <code>MongoDB</code></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> org.springframework.data.annotation.Id;
<span class="hljs-keyword">import</span> org.springframework.data.annotation.TypeAlias;
<span class="hljs-keyword">import</span> org.springframework.data.mongodb.core.mapping.Document;

<span class="hljs-keyword">import</span> lombok.Builder;
<span class="hljs-keyword">import</span> lombok.Getter;
<span class="hljs-keyword">import</span> lombok.ToString;

<span class="hljs-meta">@Getter</span>
<span class="hljs-meta">@ToString</span>
<span class="hljs-meta">@Builder(toBuilder = true)</span>
<span class="hljs-meta">@TypeAlias(value = "person")</span>
<span class="hljs-meta">@Document(collection = "persons")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> String description;
    <span class="hljs-keyword">private</span> List&lt;String&gt; hashTags;
}
</code></pre>
<h2 id="heading-start">Start</h2>
<p>We will now start our service</p>
<pre><code class="lang-powershell">./mvnw spring<span class="hljs-literal">-boot</span>:run
</code></pre>
<h2 id="heading-create">Create</h2>
<p>When a new document is created</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678605761130/3e0319b7-4ff5-4dc7-b27f-e3ef78865efd.png" alt class="image--center mx-auto" /></p>
<p>The following logs will be shown</p>
<pre><code class="lang-powershell">[<span class="hljs-number">1</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">22</span>:<span class="hljs-number">05.819</span>  INFO <span class="hljs-number">281440</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] i.d.connector.common.BaseSourceTask      : <span class="hljs-number">1</span> records sent during previous <span class="hljs-number">00</span>:<span class="hljs-number">01</span>:<span class="hljs-number">50.619</span>, last recorded offset of {rs=atlas<span class="hljs-literal">-b15fi5</span><span class="hljs-literal">-shard</span><span class="hljs-literal">-0</span>, server_id=sbd<span class="hljs-literal">-mongodb</span><span class="hljs-literal">-connector</span>} partition is {sec=<span class="hljs-number">1678605725</span>, ord=<span class="hljs-number">4</span>, transaction_id=null, resume_token=<span class="hljs-number">82640</span>D7D9D000000042B022C0100296E5A1004CCDB188FE00C4DF2852FF333EE031E5646645F69640064640D7D9DC625D06F305A0E930004}
[<span class="hljs-number">2</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">22</span>:<span class="hljs-number">05.819</span>  INFO <span class="hljs-number">281440</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] c.b.s.DebeziumSourceEventListener        : Key = <span class="hljs-string">'Struct{id={"$oid": "640d7d9dc625d06f305a0e93"}}'</span> value = <span class="hljs-string">'Struct{after={"_id": {"$oid": "640d7d9dc625d06f305a0e93"},"name": "joseph","description": "hello world","hashTags": ["hello","world"]},source=Struct{version=2.1.2.Final,connector=mongodb,name=sbd-mongodb-connector,ts_ms=1678605725000,db=source,rs=atlas-b15fi5-shard-0,collection=persons,ord=4},op=c,ts_ms=1678605725586}'</span>
</code></pre>
<ol>
<li><p>Indicates the resume token information</p>
</li>
<li><p>Created event <code>key/value</code> pair</p>
</li>
</ol>
<h2 id="heading-update">Update</h2>
<p>Let's try to update the <code>name</code> field, once updated, the following logs will be shown</p>
<pre><code class="lang-powershell">[<span class="hljs-number">1</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">26</span>:<span class="hljs-number">43.407</span>  INFO <span class="hljs-number">283436</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] i.d.connector.common.BaseSourceTask      : <span class="hljs-number">1</span> records sent during previous <span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">23.096</span>, last recorded offset of {rs=atlas<span class="hljs-literal">-b15fi5</span><span class="hljs-literal">-shard</span><span class="hljs-literal">-0</span>, server_id=sbd<span class="hljs-literal">-mongodb</span><span class="hljs-literal">-connector</span>} partition is {sec=<span class="hljs-number">1678606003</span>, ord=<span class="hljs-number">5</span>, transaction_id=null, resume_token=<span class="hljs-number">82640</span>D7EB3000000052B022C0100296E5A1004CCDB188FE00C4DF2852FF333EE031E5646645F69640064640D7D9DC625D06F305A0E930004}
[<span class="hljs-number">2</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">26</span>:<span class="hljs-number">43.410</span>  INFO <span class="hljs-number">283436</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] c.b.s.DebeziumSourceEventListener        : Key = <span class="hljs-string">'Struct{id={"$oid": "640d7d9dc625d06f305a0e93"}}'</span> value = <span class="hljs-string">'Struct{after={"_id": {"$oid": "640d7d9dc625d06f305a0e93"},"name": "bwgjoseph","description": "hello world","hashTags": ["hello","world"]},updateDescription=Struct{updatedFields={"name": "bwgjoseph"}},source=Struct{version=2.1.2.Final,connector=mongodb,name=sbd-mongodb-connector,ts_ms=1678606003000,db=source,rs=atlas-b15fi5-shard-0,collection=persons,ord=5},op=u,ts_ms=1678606003351}'</span>
</code></pre>
<ol>
<li><p>Indicates the resume token information</p>
</li>
<li><p>Updated event <code>key/value</code> pair</p>
<ol>
<li>where we can see the name is now <code>bwgjoseph</code> (changed from <code>joseph</code>)</li>
</ol>
</li>
</ol>
<h2 id="heading-delete">Delete</h2>
<p>When the document is <code>deleted</code>, it will receive 2 events</p>
<pre><code class="lang-powershell">[<span class="hljs-number">1</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">27</span>:<span class="hljs-number">24.555</span>  INFO <span class="hljs-number">283436</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] i.d.connector.common.BaseSourceTask      : <span class="hljs-number">2</span> records sent during previous <span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">41.148</span>, last recorded offset of {rs=atlas<span class="hljs-literal">-b15fi5</span><span class="hljs-literal">-shard</span><span class="hljs-literal">-0</span>, server_id=sbd<span class="hljs-literal">-mongodb</span><span class="hljs-literal">-connector</span>} partition is {sec=<span class="hljs-number">1678606044</span>, ord=<span class="hljs-number">3</span>, transaction_id=null, resume_token=<span class="hljs-number">82640</span>D7EDC000000032B022C0100296E5A1004CCDB188FE00C4DF2852FF333EE031E5646645F69640064640D7D9DC625D06F305A0E930004}
[<span class="hljs-number">2</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">27</span>:<span class="hljs-number">24.557</span>  INFO <span class="hljs-number">283436</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] c.b.s.DebeziumSourceEventListener        : Key = <span class="hljs-string">'Struct{id={"$oid": "640d7d9dc625d06f305a0e93"}}'</span> value = <span class="hljs-string">'Struct{source=Struct{version=2.1.2.Final,connector=mongodb,name=sbd-mongodb-connector,ts_ms=1678606044000,db=source,rs=atlas-b15fi5-shard-0,collection=persons,ord=3},op=d,ts_ms=1678606044425}'</span>   
[<span class="hljs-number">3</span>] <span class="hljs-number">2023</span><span class="hljs-literal">-03</span><span class="hljs-literal">-12</span> <span class="hljs-number">15</span>:<span class="hljs-number">27</span>:<span class="hljs-number">24.559</span>  INFO <span class="hljs-number">283436</span> --- [<span class="hljs-type">pool</span>-<span class="hljs-number">1</span>-<span class="hljs-type">thread</span>-<span class="hljs-number">1</span>] c.b.s.DebeziumSourceEventListener        : Key = <span class="hljs-string">'Struct{id={"$oid": "640d7d9dc625d06f305a0e93"}}'</span> value = <span class="hljs-string">'null'</span>
</code></pre>
<ol>
<li><p>Indicates the resume token information</p>
</li>
<li><p>Deleted Event 1 <code>key/value</code> pair <strong>with</strong> <code>value</code></p>
</li>
<li><p>Deleted Event 2 <code>key/value</code> pair <strong>without</strong> <code>value</code></p>
</li>
</ol>
<p>Why do we receive 2 events for deletion? I'm not sure, but it is not so useful for my use case since I would need the <code>value</code> of the <code>source and op</code> information to do something meaningful.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>It wasn't as difficult as I thought to get it started, but it did take me a day of googling around, reading the documentation, and understanding the concepts behind Debezium. I think I'm only scratching the surface though, but it's a start!</p>
<p>I think using the embedded server is a good starting point to determine if this works for you or your team without worrying about setting the entire infrastructure (i.e. Kafka, Kafka Connect) and yet achieving the same outcome.</p>
<p>When you are sure of diving into it, or when you need to scale, then maybe that is the time to have the proper infrastructure to support</p>
<p>In my next blog post, I will be writing about how to decode the event message. Stay tuned!</p>
<h1 id="heading-source-code"><strong>Source Code</strong></h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-boot-debezium-mongodb-es"><strong>GitHub</strong></a></p>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://debezium.io/documentation/reference/2.1/">https://debezium.io/documentation/reference/2.1/</a></p>
</li>
<li><p><a target="_blank" href="https://www.baeldung.com/debezium-intro">https://www.baeldung.com/debezium-intro</a></p>
</li>
<li><p><a target="_blank" href="https://hevodata.com/learn/debezium-mongodb/">https://hevodata.com/learn/debezium-mongodb/</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Prefer Docker save and load]]></title><description><![CDATA[over Docker export and import. This serves as a reminder for me as I often mixed up myself. As per documentation, save produces a tar file that contains…]]></description><link>https://bwgjoseph.com/prefer-docker-save-and-load</link><guid isPermaLink="true">https://bwgjoseph.com/prefer-docker-save-and-load</guid><category><![CDATA[Docker]]></category><category><![CDATA[air-gapped]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 18 Feb 2023 16:30:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/HSACbYjZsqQ/upload/ee674c17cc0bda42d6d906740d77a5ae.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>over Docker export and import.</p>
<p>This serves as a reminder for me as I often mixed up myself.</p>
<h2 id="heading-save-vs-export">Save vs Export</h2>
<p>As per documentation, <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/save/">save</a> produces a tar file that contains</p>
<blockquote>
<p>all parent layers, and all tags + versions, or specified repo:tag, for each argument provided</p>
</blockquote>
<pre><code class="lang-bash">docker save busybox:latest &gt; busybox.tar
</code></pre>
<p>while <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/export/">export</a> also produces a tar file, it only exports the content without layer/history</p>
<blockquote>
<p>export the contents of the <em>underlying</em> directory</p>
</blockquote>
<pre><code class="lang-bash">docker <span class="hljs-built_in">export</span> busybox:latest &gt; busybox.tar
</code></pre>
<p>What this also means is that using the <code>export</code> will result in a smaller size image due to flattening.</p>
<h2 id="heading-load-vs-import">Load vs Import</h2>
<p><a target="_blank" href="https://docs.docker.com/engine/reference/commandline/load/">load</a> restores the full history and layers from what was <code>saved</code></p>
<blockquote>
<p>Load an image or repository from a tar archive (even if compressed with gzip, bzip2, or xz) from a file or STDIN. It restores both images and tags.</p>
</blockquote>
<pre><code class="lang-bash">docker load &lt; busybox.tar
</code></pre>
<p>while <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/import/">import</a> just creates the filesystem with the <code>exported content</code></p>
<blockquote>
<p>Import the contents from a tarball to create a filesystem image</p>
</blockquote>
<pre><code class="lang-bash">docker import busybox.tar
</code></pre>
<h2 id="heading-when-to-use-one-over-another">When to use one over another?</h2>
<p>In most cases, it wouldn't matter much.</p>
<p>However, from the perspective of running the command on an internet-enabled machine vs an air-gapped machine, there is a slight difference and you should really prefer to use <code>save and load</code> combination.</p>
<p>Why? Because on an air-gapped machine, you might the full history/layers to load successfully, otherwise, you may encounter errors where there are missing layers/images. From my very very vague memory, the digest seems to be the same whether you run <code>load or import</code>.</p>
<p>References:</p>
<ul>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/36925261/what-is-the-difference-between-import-and-load-in-docker">https://stackoverflow.com/questions/36925261/what-is-the-difference-between-import-and-load-in-docker</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/22713551/how-to-flatten-a-docker-image">https://stackoverflow.com/questions/22713551/how-to-flatten-a-docker-image</a></p>
</li>
<li><p><a target="_blank" href="https://tuhrig.de/flatten-a-docker-container-or-image/">https://tuhrig.de/flatten-a-docker-container-or-image/</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[A better way to install Windows App Bundle file in offline machine]]></title><description><![CDATA[This is a follow-up to the previous article I have written on How to manually install WSL2 on a Windows 10 Virtual Machine as I learned an alternate method…]]></description><link>https://bwgjoseph.com/a-better-way-to-install-windows-app-bundle-file-in-offline-machine</link><guid isPermaLink="true">https://bwgjoseph.com/a-better-way-to-install-windows-app-bundle-file-in-offline-machine</guid><category><![CDATA[Windows]]></category><category><![CDATA[windows terminal]]></category><category><![CDATA[Ubuntu 22.04]]></category><category><![CDATA[wsl2]]></category><category><![CDATA[virtualization]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 07 Jan 2023 07:22:43 GMT</pubDate><content:encoded><![CDATA[<p>This is a follow-up to the previous article I have written on <a target="_blank" href="https://bwgjoseph.com/how-to-manually-install-wsl2-on-a-windows-10-virtual-machine">How to manually install WSL2 on a Windows 10 Virtual Machine</a> as I learned an alternate method to install Windows App Bundle (.appxbundle/.msixbundle) files.</p>
<h1 id="heading-context">Context</h1>
<p>In my previous article, I highlighted the issue of being <a target="_blank" href="https://bwgjoseph.com/how-to-manually-install-wsl2-on-a-windows-10-virtual-machine#heading-unable-to-launch-ubuntu-post-installation">unable to launch Ubuntu post installation</a> and how to resolve it by gaining access to <code>WindowsApp</code> directory. I <a target="_blank" href="https://github.com/microsoft/WSL/issues/8031#issuecomment-1370928941">have been told</a> that this is not recommended as it may cause unforeseen issues in the future.</p>
<h1 id="heading-solution">Solution</h1>
<p>Rather than gaining access to <code>WindowsApp</code> directory, and copying out the "installed files" to a separate directory. We can skip the installation step and extract the files manually, and place it somewhere we already have access.</p>
<p>Since the bundle files are just multiple files bundled together (think zip files), the content can also be extracted using the same method.</p>
<h3 id="heading-ubuntu">Ubuntu</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672848836870/20d1ebb8-9a81-4da1-80fe-493266b0f72d.gif" alt class="image--center mx-auto" /></p>
<blockquote>
<p>As I have disabled virtualization on my machine, hence the error message is shown. Please ignore it.</p>
<p>This works at the timing of writing for <code>Ubuntu2204-221101.AppxBundle</code></p>
</blockquote>
<h3 id="heading-windows-terminal">Windows Terminal</h3>
<p>Knowing the above, it also could mean that if any other application faces the same issue, we could try to resolve it using the same means. I know that <code>Windows Terminal</code> does suffer from the same issue, hence, I did it the same way to show that it can be done.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672849073060/0843e558-1f76-49d8-a831-6520794b491b.gif" alt class="image--center mx-auto" /></p>
<blockquote>
<p>This works at the time of writing for <code>Microsoft.WindowsTerminal_Win10_1.15.3465.0_8wekyb3d8bbwe.msixbundle</code></p>
</blockquote>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I do think that this is a better solution compared to gaining access to <code>WindowsApp</code> directory.</p>
<p>If you have any other better method, please let me know!</p>
<h1 id="heading-reference">Reference</h1>
<ul>
<li><a target="_blank" href="https://github.com/microsoft/WSL/issues/8031">https://github.com/microsoft/WSL/issues/8031</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Review on 2022, Goals for 2023]]></title><description><![CDATA[When I started this blog on 1st Jan 2022, I mentioned that I wanted to write one post per month and I achieved my goal. It wasn't too difficult, although…]]></description><link>https://bwgjoseph.com/review-on-2022-goals-for-2023</link><guid isPermaLink="true">https://bwgjoseph.com/review-on-2022-goals-for-2023</guid><category><![CDATA[reflection]]></category><category><![CDATA[goals]]></category><category><![CDATA[2023]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 31 Dec 2022 16:07:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/543ac073bc0f0282070e1064937a8a77.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When I started this blog on <a target="_blank" href="https://bwgjoseph.com/resolution-for-2022">1st Jan 2022</a>, I mentioned that I wanted to write one post per month and I achieved my goal. It wasn't too difficult, although there are months that I didn't write any at all, and months that I write 2-3 per month.</p>
<p>I wrote a total of 17 articles (excluding the first entry), and the top 3 views are</p>
<ul>
<li><p><a target="_blank" href="https://bwgjoseph.com/how-to-setup-and-configure-your-own-gitlab-runner">How to setup and configure your own Gitlab Runner</a> at ~1.3k view</p>
</li>
<li><p><a target="_blank" href="https://bwgjoseph.com/how-to-configure-lombok-extension-to-play-well-with-vscode">How to configure Lombok extension to play well with VSCode</a> at ~1.1k view</p>
</li>
<li><p><a target="_blank" href="https://bwgjoseph.com/enhance-your-wsl-2-experience-with-xfce4">Enhance your WSL 2 experience with Xfce4</a> at ~500 view</p>
</li>
</ul>
<p>The total views at the time of writing are <strong>5147</strong>, not bad at all. I don't think about getting high views, but more of hoping that the articles I wrote help someone in need.</p>
<p>I still have around 10 articles in my draft, some have been there for quite some time, and I never got around to finishing up the article.</p>
<p>Overall, I think I did well and writing has helped me understand the topic (I wrote) much deeper. There is so much research and work behind the scene to get the article out.</p>
<p>In 2023, I hoped to achieve the following</p>
<ul>
<li><p>Continue to write at least one article per month</p>
</li>
<li><p>Finish reading <a target="_blank" href="https://www.manning.com/books/modern-java-in-action">Modern Java in Action</a></p>
</li>
<li><p>Create a schedule to watch tech videos (I kept putting them off)</p>
</li>
<li><p>Learn more in-depth about Kubernetes</p>
</li>
</ul>
<p>Have a great year ahead!</p>
]]></content:encoded></item><item><title><![CDATA[Can you use Lombok toBuilder on an Abstract Class?]]></title><description><![CDATA[Yes, you can, and you just need an additional line of code in the Abstract Class. Let's take a look at how we can do so. If you have an abstract class with…]]></description><link>https://bwgjoseph.com/can-you-use-lombok-tobuilder-on-an-abstract-class</link><guid isPermaLink="true">https://bwgjoseph.com/can-you-use-lombok-tobuilder-on-an-abstract-class</guid><category><![CDATA[lombok]]></category><category><![CDATA[Java]]></category><category><![CDATA[inheritance]]></category><category><![CDATA[builder pattern]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Fri, 30 Dec 2022 08:09:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672387526205/e7c62f58-a32d-4fe6-9b5e-39f6d94d0569.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Yes, you can, and you just need an additional line of code in the <code>Abstract Class</code>. Let's take a look at how we can do so.</p>
<h1 id="heading-context">Context</h1>
<p>If you have an abstract class with various subclasses, and you need to define some values through <code>builder</code> method, you won't be able to do so by default because Lombok does not know if all the subclasses are annotated with <code>toBuilder</code> but we can force all subclasses to implement <code>toBuilder</code> method.</p>
<h1 id="heading-setup">Setup</h1>
<p>To make it simple, we only have an abstract class with 2 subclasses, and a couple of fields.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SuperBuilder(toBuilder = true)</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddressDO</span> </span>{
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-keyword">private</span> String street;
    <span class="hljs-keyword">private</span> String postalCode;
    <span class="hljs-keyword">private</span> String unit;
}

<span class="hljs-meta">@SuperBuilder(toBuilder = true)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomeAddressDO</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddressDO</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> isRental;
}

<span class="hljs-meta">@SuperBuilder(toBuilder = true)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OfficeAddressDO</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddressDO</span> </span>{
    <span class="hljs-keyword">private</span> String building;
}
</code></pre>
<p>Now, imagine we have a method that takes in <code>AddressDO</code> as the argument</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> AddressDO <span class="hljs-title">createAddress</span><span class="hljs-params">(AddressDO addressDO)</span> </span>{
    <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">return</span> addressDO;
}
</code></pre>
<ul>
<li>We would like to call <code>toBuilder</code> on <code>addressDO</code> to define some fields</li>
</ul>
<h1 id="heading-problem">Problem</h1>
<p>Take a look at the GIF below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672384694804/56ca8276-62e4-4b6b-9d48-954d3d6e781b.gif" alt class="image--center mx-auto" /></p>
<p>From the GIF, we can see that even though we defined <code>@SuperBuilder(toBuilder = true)</code>, we are unable to call <code>toBuilder</code> method. As mentioned above, this is done on purpose by <a target="_blank" href="https://stackoverflow.com/a/61651054/1778855">Lombok</a>, since it cannot ensure all subclasses are annotated with <code>toBuilder</code>.</p>
<h1 id="heading-resolution">Resolution</h1>
<p>So how can we resolve this?</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddressDO</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> AddressDOBuilder&lt;?, ?&gt; toBuilder(); <span class="hljs-comment">// added this</span>
    <span class="hljs-comment">// omitted</span>
}
</code></pre>
<p>We create an abstract <code>toBuilder</code> method which will ensure that all subclasses also implement this method.</p>
<p>This is what happens if the subclass did not implement <code>toBuilder</code> method</p>
<pre><code class="lang-plaintext">The type HomeAddressDO must implement the inherited abstract method AddressDO.toBuilder()
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672385840262/f89f89c0-a900-4a36-b68e-06decda733b9.png" alt class="image--center mx-auto" /></p>
<p>And now, if we try again</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672385983305/b23207e4-e7cf-4dd1-9a0a-e596b5342288.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-limitation">Limitation</h2>
<p>The limitation is that it only allows for modification to the fields on the abstract class unless we cast it first. However, if we were to cast it, then there is no (less) need for the <code>abstract method</code> in the first place.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672386197077/90e96406-9c3e-46a2-b9f5-326fbac4d30b.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>We have seen how we can overcome the limitation of calling <code>toBuilder</code> in an abstract class, and the limitation of doing so. I wouldn't call this a hack, but do use it only when you need it.</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-boot-lombok-abstract-class-tobuilder">GitHub</a></p>
]]></content:encoded></item><item><title><![CDATA[Polymorphic DTO using Java Record with Jackson]]></title><description><![CDATA[With the introduction of Java Record class, it becomes the perfect candidate to use as a Data Transfer Object (DTO). I'm not going to explain more, you can…]]></description><link>https://bwgjoseph.com/polymorphic-dto-using-java-record-with-jackson</link><guid isPermaLink="true">https://bwgjoseph.com/polymorphic-dto-using-java-record-with-jackson</guid><category><![CDATA[Java]]></category><category><![CDATA[polymorphism]]></category><category><![CDATA[jackson]]></category><category><![CDATA[api]]></category><category><![CDATA[Spring framework]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Wed, 28 Dec 2022 16:47:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671550069770/WnAEPZ9hx.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>With the introduction of <code>Java Record</code> class, it becomes the perfect candidate to use as a <code>Data Transfer Object (DTO)</code>. I'm not going to explain more, you can find tons of articles out there with its benefit and code samples.</p>
<p>However, what is missing out there is a code sample of how to use it with a Polymorphic DTO use case where we know that <code>Java Record</code> classes cannot be extended but can implement interfaces.</p>
<p>I'm going to show you how we can achieve this together with <code>Jackson</code></p>
<h1 id="heading-scenario">Scenario</h1>
<p>Imagine we have an API endpoint that accepts <code>HomeAddressDto</code> and <code>OfficeAddressDto</code> as the <code>@RequestBody</code>, which would look like the following:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">HomeAddressDto</span><span class="hljs-params">(String street, String postalCode, String unit)</span> </span>{}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">OfficeAddressDto</span><span class="hljs-params">(String building, String street, String postalCode, String unit)</span> </span>{}

<span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/addresses")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddressController</span> </span>{

    <span class="hljs-meta">@PostMapping("/home")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> HomeAddressDto <span class="hljs-title">create</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> HomeAddressDto homeAddressDto)</span> </span>{
        <span class="hljs-keyword">return</span> homeAddressDto;
    }

    <span class="hljs-meta">@PostMapping("/office")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> OfficeAddressDto <span class="hljs-title">create</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> OfficeAddressDto officeAddressDto)</span> </span>{
        <span class="hljs-keyword">return</span> officeAddressDto;
    }
}
</code></pre>
<p>Now, there is nothing wrong with this, and it works, but it can be pretty ugly having to create different endpoints to cater to each different (but of the same type) DTO. It can get messy real fast.</p>
<p>Let's see if we can improve this.</p>
<h1 id="heading-solution">Solution</h1>
<h2 id="heading-step-1-common-interface">Step 1: Common Interface</h2>
<p>Since we know that both types are address, we can create an empty interface to house both classes.</p>
<blockquote>
<p>Remember, <code>Java Record</code> cannot be extended</p>
</blockquote>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Address</span> </span>{}
</code></pre>
<p>Then we update both classes to implement <code>Address</code> interface</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">HomeAddressDto</span><span class="hljs-params">(String street, String postalCode, String unit)</span> implements Address </span>{}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">OfficeAddressDto</span><span class="hljs-params">(String building, String street, String postalCode, String unit)</span> implements Address </span>{}
</code></pre>
<p>This way, it allows us to specify <code>Address</code> as the <code>@RequestBody</code></p>
<h2 id="heading-step-2-common-endpoint">Step 2: Common Endpoint</h2>
<p>Given that we have <code>Address</code> interface, we probably can work on having a single endpoint to cater to both types of address classes.</p>
<pre><code class="lang-java"><span class="hljs-meta">@PostMapping</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Address <span class="hljs-title">create</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Address address)</span> </span>{
    <span class="hljs-keyword">return</span> address;
}
</code></pre>
<p>Let's try to hit that new endpoint</p>
<pre><code class="lang-bash">curl -X POST -H <span class="hljs-string">"Content-Type: application/json"</span> -d <span class="hljs-string">"@address.json"</span> localhost:8080/addresses | jq <span class="hljs-string">'.'</span>
</code></pre>
<ul>
<li><p>Perform a curl POST request to localhost:8080/addresses</p>
</li>
<li><p>Using <code>address.json</code> content</p>
</li>
<li><p>Format output (pretty print) using <code>jq</code></p>
</li>
</ul>
<p>The content of <code>address.json</code> is</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
    <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
    <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>
}
</code></pre>
<p>And this is what we will get back</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"timestamp"</span>: <span class="hljs-string">"2022-12-20T14:44:10.836+00:00"</span>,
  <span class="hljs-attr">"status"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">"error"</span>: <span class="hljs-string">"Internal Server Error"</span>,
  <span class="hljs-attr">"trace"</span>: <span class="hljs-string">"org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]\r\n\tat"</span>, <span class="hljs-comment">// omitted</span>
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Type definition error: [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]"</span>,
  <span class="hljs-attr">"path"</span>: <span class="hljs-string">"/addresses"</span>
}
</code></pre>
<p>So what happens? Because the <code>@RequestBody</code> is using an interface, <code>Jackson</code> is not able to construct the class, hence the error message "abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information"</p>
<p>Is it possible to overcome this? Fortunately, yes, and it is commonly used in <code>Java Classes</code> with inheritance. But in this case, we want to do it in <code>Java Record</code></p>
<h2 id="heading-step-3-jackson-polymorphism-support">Step 3: Jackson Polymorphism Support</h2>
<p><code>Jackson</code> has support for polymorphic classes using <code>@JsonTypeInfo</code> and <code>@JsonSubTypes</code>, but almost all samples (online) are used based on <code>Class</code> instead of <code>Record</code>.</p>
<h3 id="heading-deduction-based-polymorphism">Deduction Based Polymorphism</h3>
<p>This is the first approach that I am going to show</p>
<pre><code class="lang-java"><span class="hljs-meta">@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)</span>
<span class="hljs-meta">@JsonSubTypes({
    @Type(HomeAddressDto.class),
    @Type(OfficeAddressDto.class)
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Address</span> </span>{}
</code></pre>
<ul>
<li><p>Using <code>Deduction</code> based approach (available since 2.12)</p>
</li>
<li><p>Declare the various subclasses</p>
</li>
</ul>
<p>If your subclasses have distinct fields, this approach is the easiest, as Jackson will assign to the correct class based on the field.</p>
<p>In this case, the difference between <code>HomeAddressDto</code> and <code>OfficeAddressDto</code> is that <code>OfficeAddressDto</code> has an additional field - <code>building</code>. If we fire the same API request, this is what we will get back</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"timestamp"</span>: <span class="hljs-string">"2022-12-20T14:58:25.515+00:00"</span>,
  <span class="hljs-attr">"status"</span>: <span class="hljs-number">400</span>,
  <span class="hljs-attr">"error"</span>: <span class="hljs-string">"Bad Request"</span>,
  <span class="hljs-attr">"trace"</span>: <span class="hljs-string">"org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Could not resolve subtype of [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]: Cannot deduce unique subtype of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (2 candidates match); nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]: Cannot deduce unique subtype of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (2 candidates match)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream)"</span>, <span class="hljs-comment">// omitted</span>
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"JSON parse error: Could not resolve subtype of [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]: Cannot deduce unique subtype of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (2 candidates match); nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address]: Cannot deduce unique subtype of `com.bwgjoseph.springbootpolymorphicjavarecordwithjackson.deduction.Address` (2 candidates match)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 59]"</span>,
  <span class="hljs-attr">"path"</span>: <span class="hljs-string">"/addresses"</span>
}
</code></pre>
<p>The error message, "2 candidates match" tells us that it is not able to automatically deduce based on the given field and thus, it throws the error. If we update the <code>json</code> to include <code>building</code> field</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"building"</span>: <span class="hljs-string">"building"</span>,
    <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
    <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
    <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>
}
</code></pre>
<p>And run the same request again. This time, it will be successful and returns the following response.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"building"</span>: <span class="hljs-string">"building"</span>,
  <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
  <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
  <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>
}
</code></pre>
<p>It works, but as I have mentioned earlier, this is great if you have distinct fields to allow <code>Jackson</code> to make the correct deduction. Although, it is also possible to tell <code>Jackson</code> which is the default class to deduce into</p>
<pre><code class="lang-java"><span class="hljs-meta">@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = HomeAddressDto.class)</span>
<span class="hljs-meta">@JsonSubTypes({
    @Type(HomeAddressDto.class),
    @Type(OfficeAddressDto.class)
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Address</span> </span>{}
</code></pre>
<ul>
<li>Notice the <code>defaultImpl = HomeAddressDto.class</code>, this tells <code>Jackson</code> to fall back to this class if you can't figure out which one to match</li>
</ul>
<p>If it works for your use case, then great, otherwise, there is also another "strategy" you can use that is <code>Name</code> based approach</p>
<h3 id="heading-name-based-polymorphism">Name Based Polymorphism</h3>
<p>This approach relies on a separate field to tell <code>Jackson</code> how to map to the correct subclass.</p>
<pre><code class="lang-java"><span class="hljs-meta">@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)</span>
<span class="hljs-meta">@JsonSubTypes({
    @Type(value = HomeAddressDto.class, name = "home"),
    @Type(value = OfficeAddressDto.class, name = "office")
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Address</span> </span>{}
</code></pre>
<ul>
<li><p>We now use <code>NAME</code> instead of <code>DEDUCTION</code> in <code>@JsonTypeInfo</code></p>
</li>
<li><p>We now specify <code>name</code> within the <code>JsonSubTypes</code>, giving its unique identifier</p>
</li>
</ul>
<p>With that, we have to hint <code>Jackson</code> by annotating <code>@JsonTypeName</code> on the individual class</p>
<pre><code class="lang-java"><span class="hljs-meta">@JsonTypeName("home")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">HomeAddressDto</span><span class="hljs-params">(String street, String postalCode, String unit)</span> implements Address </span>{}

<span class="hljs-meta">@JsonTypeName("office")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">OfficeAddressDto</span><span class="hljs-params">(String building, String street, String postalCode, String unit)</span> implements Address </span>{}
</code></pre>
<blockquote>
<p><code>@JsonTypeName</code> has to match the name defined in <code>@JsonSubTypes</code></p>
</blockquote>
<p>Next, update the <code>address.json</code> to include <code>@type</code> field</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
    <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
    <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>,
    <span class="hljs-attr">"@type"</span>: <span class="hljs-string">"home"</span>
}
</code></pre>
<ul>
<li>Added <code>@type</code> field where the value should match the value that is defined in <code>@JsonSubTypes</code></li>
</ul>
<p>And if we were to run the request via curl again. This would be the response.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"@type"</span>: <span class="hljs-string">"home"</span>,
  <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
  <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
  <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>
}
</code></pre>
<h3 id="heading-enum-based-polymorphism">Enum Based Polymorphism</h3>
<p>This last approach is pretty much the same as the previous method, only that we are going to use <code>enum</code> instead of a <code>string</code> value.</p>
<pre><code class="lang-java"><span class="hljs-meta">@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")</span>
<span class="hljs-meta">@JsonSubTypes({
    @Type(value = HomeAddressDto.class, name = "home"),
    @Type(value = OfficeAddressDto.class, name = "office")
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Address</span> </span>{}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">HomeAddressDto</span><span class="hljs-params">(String street, String postalCode, String unit)</span> implements Address </span>{}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">OfficeAddressDto</span><span class="hljs-params">(String building, String street, String postalCode, String unit)</span> implements Address </span>{}
</code></pre>
<ul>
<li><p>Notice that we added <code>property</code></p>
</li>
<li><p>It no longer requires adding <code>@JsonTypeName</code> on the respective <code>Dto</code></p>
</li>
</ul>
<p>We need to create a new <code>enum</code> class</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Type</span> </span>{
    HOME,
    OFFICE
}
</code></pre>
<p>And if we were to run the request via curl again. This would be the response.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"type"</span>: <span class="hljs-string">"home"</span>,
  <span class="hljs-attr">"street"</span>: <span class="hljs-string">"st"</span>,
  <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"pc"</span>,
  <span class="hljs-attr">"unit"</span>: <span class="hljs-string">"u"</span>
}
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>We have seen how to use Polymorphic DTO using Java Record combined with Jackson to make our endpoint much cleaner and easier to manage.</p>
<p>I am not aware of any downside to this approach yet, or if it does not work for the more complicated use cases. If you know any, drop a comment below!</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, the full source code is available on <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-boot-polymorphic-java-record-with-jackson">GitHub</a></p>
]]></content:encoded></item><item><title><![CDATA[How to manually install WSL2 on a Windows 10 Virtual Machine]]></title><description><![CDATA[I finally, finally get WSL2 to run in a Virtual Machine running on VMWare Player v17.0.0 after hours and hours of trial and error and research and tons and…]]></description><link>https://bwgjoseph.com/how-to-manually-install-wsl2-on-a-windows-10-virtual-machine</link><guid isPermaLink="true">https://bwgjoseph.com/how-to-manually-install-wsl2-on-a-windows-10-virtual-machine</guid><category><![CDATA[wsl2]]></category><category><![CDATA[virtualization]]></category><category><![CDATA[offline]]></category><category><![CDATA[Windows]]></category><category><![CDATA[vmware]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Mon, 05 Dec 2022 00:16:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670162031335/gQIxip4Y-.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I finally, finally get <code>WSL2</code> to run in a Virtual Machine running on <strong>VMWare Player v17.0.0</strong> after hours and hours of trial and error and research and tons and tons of reading. And that's not the best part, the best part is I also managed to get it working in an air-gapped (offline) environment. I'm so glad that I finally get it to work, and also gained some insights into the various technical aspect of virtualization.</p>
<p>I'm quite sure this will work for most, if not all, scenarios. I will be going through the steps by steps guide, as well as the possible error or issues you may encounter along the way, and how to overcome them (See <a class="post-section-overview" href="#heading-troubleshooting">troubleshooting section</a>).</p>
<blockquote>
<p>This guide is targeted at an air-gapped environment context where no internet is available within the virtual machine. However, it is also useful for those who want to know how to enable and run nested virtualization within a VM</p>
</blockquote>
<h1 id="heading-context">Context</h1>
<p>I am exploring ways to enable virtualization within a virtual machine (VM) which is also sometimes referred to as nested virtualization.</p>
<p>The diagram below shows an overview of what I am trying to achieve.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670001181582/7d269317-d9ec-4e78-86aa-2f1451dbdac4.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>This is the host machine</p>
</li>
<li><p>VMWare Player is installed on the host machine where</p>
</li>
<li><p>I create a Windows 10 virtual machine using VMWare Player</p>
</li>
<li><p>Within the virtual machine, I want to run WSL2 on it</p>
</li>
</ol>
<h1 id="heading-challenge">Challenge</h1>
<p>So what's exactly the challenge about getting this to work? Well, before I got it to work, it seems like an impossible task, but after I made it work, it seems like just getting the right pieces together which consist mainly on</p>
<ul>
<li><p>Enable nested virtualization to work on VMWare Player</p>
<ul>
<li>Where the host machine is also running virtualization (e.g Hyper-V)</li>
</ul>
</li>
<li><p>Manual installation of Linux Kernel Package, WSL2, and Linux Distribution (i.e. Ubuntu)</p>
</li>
<li><p>Most importantly, to get it to work in an air-gapped (offline) environment</p>
</li>
</ul>
<p>Seem easy enough, ain't it? Let's see how we can do it in this article</p>
<h1 id="heading-setup">Setup</h1>
<p>In my setup, these are the following Operating Systems and Applications versions used at the time of writing.</p>
<table><tbody><tr><td><p><strong>Host Machine</strong></p></td><td><p>Windows 10 x64 Version 22H2 (Build 19045.2251)</p></td></tr><tr><td><p><strong>VMWare</strong></p></td><td><p>VMware® Workstation 17 Player 17.0.0 build-20800274</p></td></tr><tr><td><p><strong>Virtual Machine</strong></p></td><td><p>Windows 10 x64 Version 22H2 (ISO Image build using Windows Media Tool)</p></td></tr><tr><td><p><strong>WSL</strong></p></td><td><p>WSL2 v1.0.0</p></td></tr><tr><td><p><strong>WSL Kernel</strong></p></td><td><p>5.10.16</p></td></tr><tr><td><p><strong>Linux Distribution</strong></p></td><td><p>Ubuntu 22.04 LTS</p></td></tr></tbody></table>

<p>While I used VMWare Player to test it out, this should work for <code>Oracle VM VirtualBox</code> or even <code>Hyper-V</code> as well</p>
<blockquote>
<p>For 3rd party hypervisors such as VMWare, or VirtualBox. Please ensure it is at least <a target="_blank" href="https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html">Version 15.5</a> and <a target="_blank" href="https://www.virtualbox.org/wiki/Changelog-6.0">Version 6.0</a> respectively</p>
<p>For Hyper-V, see <a target="_blank" href="https://learn.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/nested-virtualization">this</a></p>
</blockquote>
<h1 id="heading-preparation">Preparation</h1>
<p>Since this is based on the assumption of installing and running on an air-gapped environment, you will not have access to the internet within the VM, and these are the installers you will need to download first on the host machine (or elsewhere), and later port into the VM.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Application</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://www.microsoft.com/en-au/software-download/windows10">Windows 10 Installation Media</a></td><td>Prepare Windows 10 x64 22H2 ISO image</td></tr>
<tr>
<td><a target="_blank" href="https://www.vmware.com/asean/products/workstation-player.html">VMware Player</a></td><td>Hypervisor to run a virtual machine</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/microsoft/WSL/releases">WSL</a></td><td>Windows Subsystem for Linux</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package">WSL2 Linux Kernel Update Package</a></td><td>Update Linux Kernel to support WSL2</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/windows/wsl/install-manual#downloading-distributions">Ubuntu 22.04 LTS Distribution</a></td><td>WSL Linux distributions</td></tr>
</tbody>
</table>
</div><p>I won't be going through how to create an image or install VMWare Player, as these are not the focus of this article. There are plenty of great articles out there on how to do those.</p>
<p>My assumption is that you already have VMWare Player installed.</p>
<h2 id="heading-enable-virtualization-in-bios">Enable Virtualization in BIOS</h2>
<p>I think at this current time and age, virtualization would be enabled on your BIOS by default, and you probably need not change anything, especially if you are already running some sort of virtualized work on your host machine such as running Hyper-V, Docker Desktop and so on.</p>
<p>Otherwise, you can follow this <a target="_blank" href="https://support.bluestacks.com/hc/en-us/articles/360058102252-How-to-enable-Virtualization-VT-on-Windows-10-for-BlueStacks-5">excellent guide</a> on how to enable it in your BIOS.</p>
<h2 id="heading-disable-hypervisor-on-host-machine">Disable Hypervisor on host machine</h2>
<p>This can be said to be the <strong>most important step</strong> because without disabling the hypervisor on the host machine, VMWare virtual machine <strong>cannot be</strong> configured to use nested virtualization as the option will be greyed out</p>
<ul>
<li><p>Launch terminal with <strong>administrator rights</strong></p>
</li>
<li><p>Run <code>bcdedit</code> and see something along this line</p>
</li>
</ul>
<pre><code class="lang-bash">&gt; bcdedit

Windows Boot Loader
-------------------
identifier              {current}
device                  partition=C:
path                    \WINDOWS\system32\winload.efi
description             Windows 10
locale                  en-US
inherit                 {bootloadersettings}
recoverysequence        {61b00ac8-16d1-xxxx-xxxx-xxxxxxxxxxxx}
volumebandid            2
displaymessageoverride  Recovery
recoveryenabled         Yes
isolatedcontext         Yes
allowedinmemorysettings 0x15000075
osdevice                partition=C:
systemroot              \WINDOWS
resumeobject            {61b00ac6-16d1-xxxx-xxxx-xxxxxxxxxxxx}
nx                      OptIn
bootmenupolicy          Standard
hypervisorlaunchtype    Auto
</code></pre>
<ul>
<li><p>Focus on the last item - <code>hypervisorlaunchtype</code></p>
<ul>
<li>We need to set this to <code>off</code> by running the following command</li>
</ul>
</li>
</ul>
<pre><code class="lang-bash">bcdedit /<span class="hljs-built_in">set</span> hypervisorlaunchtype off
</code></pre>
<ul>
<li><p>It does not provide any sort of feedback to indicate that the changes is made</p>
</li>
<li><p>After running the command, reboot your machine manually</p>
</li>
</ul>
<p>If you look around enough, there will be various other ways to achieve <code>nested virtualization</code> but in my opinion, this method should be the least intrusive and most easy. Why? Because you only need to run a single command and reboot your host machine and it does (should) not cause any side-effect to your existing virtualization software or tools or configuration.</p>
<p>What this command does is essentially disable the hypervisor (i.e. <code>Hyper-V</code>) from running on the host machine, and allow VMWare to enable <code>nested virtualization</code></p>
<p>This is how it looks like on my host machine</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670136600790/g_90BSMRN.gif" alt class="image--center mx-auto" /></p>
<p>Everything is still intact</p>
<p>What this means is that you can't use Hyper-V, Docker Desktop or any other virtualization stuff on your host machine while allowing nested virtualization to happen. But it also means that whenever you do not need to use nested virtualization, you can simply run the following command to disable it and you can continue to use virtualization stuff on your host machine.</p>
<pre><code class="lang-bash">bcdedit /<span class="hljs-built_in">set</span> hypervisorlaunchtype auto
</code></pre>
<p>With that, we are all set to create our VM, install Windows 10 OS, and WSL2</p>
<h1 id="heading-steps">Steps</h1>
<h2 id="heading-creating-virtual-machine">Creating Virtual Machine</h2>
<ul>
<li><p>Launch VMWare Player</p>
</li>
<li><p>Click <code>Create a new Virtual Machine</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670041831980/ec5650f4-845f-42ee-8023-6047763309a5.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Browse to the <code>iso file</code> and click <code>Next &gt;</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670041893530/cdd79817-ad94-4f21-b03b-875d3dd64e51.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Give your virtual machine a name and click <code>Next &gt;</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670041946353/be3ab827-0e47-4e05-b4dd-fbcd4b07f376.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Click <code>Next &gt;</code> when asked for <code>Disk Capacity</code>. The default is <code>60GB</code></p>
</li>
<li><p>Click on <code>Customize Hardware</code></p>
<ul>
<li><p><strong>Memory</strong>: Adjust your memory as you wish, I do recommend at least <code>4GB</code></p>
</li>
<li><p><strong>Processors</strong>: Check <code>Virtualize Intel VT-x/EPT or AMD-V/RVI</code> to allow for nested virtualization</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670042786160/d76aa3f8-5de0-4eb8-bf43-e561c7c562a4.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>This is the most important step, ensure that this option is checked. If this section is greyed out, ensure you have done the preparation, or go through the troubleshooting guide</p>
</blockquote>
</li>
<li><p><strong>Network Adapter</strong>: Uncheck <code>Connect at power on</code> to simulate an offline environment</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670042758500/f9110217-80b9-4bc7-9f5f-98b367167f4d.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
</li>
<li><p>Click <code>Close</code> once done</p>
</li>
<li><p>Click <code>Finish</code> to start the creation of the virtual machine. It will auto-power on right after the creation</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670042604193/fa9f044a-f1ed-46dc-aa6f-155e0a33379c.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Continue with the installation of <strong>Windows 10</strong></p>
</li>
</ul>
<h2 id="heading-installing-windows-10-os">Installing Windows 10 OS</h2>
<p>I will not go through the step-by-step for this section, only highlight certain parts to take note of during the installation</p>
<ul>
<li><p>Select <code>Windows 10 Pro</code> when prompted</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670043176837/8d9e14be-c73d-4851-8536-288419fe6613.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Select <code>I don't have internet</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670043631995/d504acd3-1c04-4d97-b474-415543330626.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Select <code>Continue with limited setup</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670043678479/6470daf2-bfe8-4a6d-be22-f2fbb32ef009.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h2 id="heading-post-os-installation">Post OS Installation</h2>
<p>There are a couple of things we need to do before the actual installation of WSL2</p>
<h3 id="heading-vmware-tools">VMWare Tools</h3>
<p>This is not exactly required to run WSL2, but more to improve your experience while managing virtual machine(s) and more seamless interaction</p>
<ul>
<li><p>Select <code>Player &gt; Manage &gt; Install VMWare Tools...</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670044283825/633f3708-0b49-485f-9021-70003306f278.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>It will then be mounted as a drive within the VM</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670044404507/63df29d6-f4f7-4888-a857-44829daac4ab.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Double-click to launch it</p>
</li>
<li><p>Follow the screen instruction to install it</p>
<ul>
<li>Select <code>Complete</code> setup type when prompted</li>
</ul>
</li>
<li><p>Restart VM after installation is completed</p>
</li>
</ul>
<h3 id="heading-copy-files-to-vm">Copy files to VM</h3>
<p>Since we are working in offline mode, we have to copy files from the host machine to the VM by simply dragging the files from the host machine directory into the VM directory as shown in the gif below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670046129295/136b6179-5923-4708-85d7-e98eb6b47a26.gif" alt class="image--center mx-auto" /></p>
<p>You will only require the following files for the rest of the guide</p>
<ul>
<li><p>Microsoft.WSL_1.0.0.0_x64_ARM64.msixbundle</p>
</li>
<li><p>Ubuntu2204-221101.AppxBundle</p>
</li>
<li><p>wsl_update_x64.msi</p>
</li>
</ul>
<blockquote>
<p>Your filename may differ if you came from the future, as the version number will likely be different</p>
</blockquote>
<h2 id="heading-installing-wsl2">Installing WSL2</h2>
<p>Now that we have the required files within the VM, we can now start the actual installation of WSL2.</p>
<blockquote>
<p>If you are working on an internet-enabled machine, you can simply run <code>wsl --install</code> which will enable the necessary components, update the kernel, and install <code>Ubuntu</code> as the default Linux distribution</p>
</blockquote>
<h3 id="heading-windows-features">Windows Features</h3>
<p>First, let's take a look at the current state of the <code>Windows Features</code> inside our VM</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670160123491/jHzGWO-7w.png" alt class="image--center mx-auto" /></p>
<p>The two key components are now unchecked</p>
<ul>
<li><p>Virtual Machine Platform</p>
</li>
<li><p>Windows Subsystem for Linux</p>
</li>
</ul>
<blockquote>
<p>WSL is now <a target="_blank" href="https://devblogs.microsoft.com/commandline/the-windows-subsystem-for-linux-in-the-microsoft-store-is-now-generally-available-on-windows-10-and-11/">generally available</a> (GA) in Windows Store since 22 Nov 2022</p>
</blockquote>
<h3 id="heading-enable-wsl-component">Enable WSL component</h3>
<ul>
<li><p>Launch <code>PowerShell</code> as administrator</p>
</li>
<li><p>Run <code>dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670146124087/YY1vfbR1w.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h3 id="heading-enable-virtual-machine-platform">Enable Virtual Machine Platform</h3>
<ul>
<li><p>Run <code>dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670146228389/o21sAMJcb.png" alt /></p>
</li>
<li><p>Reboot your machine</p>
</li>
</ul>
<h3 id="heading-install-linux-kernel-package">Install Linux Kernel Package</h3>
<ul>
<li><p>Navigate to the directory where the files are located at</p>
</li>
<li><p>Double-click on <code>wsl_update_x64.msi</code></p>
</li>
<li><p>Follow on-screen instruction</p>
</li>
<li><p>After installed, run <code>wsl --status</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670146676384/NH5UymAj7.png" alt /></p>
<blockquote>
<p>The kernel version at the time of writing is <strong>5.10.16</strong></p>
</blockquote>
</li>
</ul>
<h3 id="heading-install-wsl-2">Install WSL 2</h3>
<ul>
<li><p>Launch <code>PowerShell</code> as administrator</p>
</li>
<li><p>Navigate to the directory where the files are located at</p>
</li>
<li><p>Run <code>Add-AppxPackage .\Microsoft.WSL_1.0.0.0_x64_ARM64.msixbundle</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670063569228/b5943c3d-9b29-4baa-9474-32f48f8da6d7.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h3 id="heading-set-default-wsl-version">Set default WSL version</h3>
<ul>
<li>Run <code>wsl --set-default-version 2</code></li>
</ul>
<h2 id="heading-install-ubuntu-2204-lts">Install Ubuntu 22.04 LTS</h2>
<p>[Update 7th Jan 2023]: Please follow the instructions <a target="_blank" href="https://bwgjoseph.com/a-better-way-to-install-windows-app-bundle-file-in-offline-machine">here</a> to extract the necessary files and install Ubuntu, and ignore the steps below</p>
<ul>
<li><p>[continue from above]</p>
</li>
<li><p>Run <code>Add-AppxPackage .\Ubuntu2204-221101.AppxBundle</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670064373698/857413b7-d988-4c62-b6a9-3418caeb8bb5.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Once completed, follow the instruction <a class="post-section-overview" href="#heading-unable-to-launch-ubuntu-post-installation">here</a> to gain access to the <code>WindowsApp</code> directory (I'll wait)</p>
</li>
<li><p>Once you have gained access and copied the files</p>
</li>
<li><p>Navigate to the directory</p>
</li>
<li><p>Double-click on <code>ubuntu.exe</code></p>
</li>
<li><p>Follow the on-screen instruction to finish the rest of the setup</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670070449311/bad0d105-c20c-468b-94ca-eb078541575e.gif" alt class="image--center mx-auto" /></p>
</li>
</ul>
<blockquote>
<p>While the workaround works, you cannot launch it via the <code>Start Menu</code> but you can pin it to the taskbar, or create a shortcut on your desktop to launch it</p>
</blockquote>
<p>Congratulations! You have completed all the steps necessary to reach the goal we set at the start.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope that this article helps someone else who is looking into performing manual installation of WSL2 on a virtual machine in an air-gapped environment and sharing solutions to overcome some of the issues you may face along the way.</p>
<p>Give a thumbs-up if you find this article useful.</p>
<hr />
<h1 id="heading-troubleshooting">Troubleshooting</h1>
<h2 id="heading-virtualized-intel-vt-xept-is-not-supported-on-this-platform">Virtualized Intel VT-x/EPT is not supported on this platform</h2>
<p>I have previously encountered an issue where I disabled all four components of the <code>Windows Features</code>, and I can check <code>Virtualize Intel VT-x/EPT or AMD-V/RVI</code> in VMWare VM Settings but yet it still complains something along this line when the VM is starting</p>
<pre><code class="lang-bash">Virtualized Intel VT-x/EPT is not supported on this platform.

Continue without virtualized Intel VT-x/EPT?
</code></pre>
<p>The solution is simply going into BIOS and triggering a "reset" of the virtualization setting. All thanks to the following <a target="_blank" href="https://github.com/microsoft/WSL/issues/5363#issuecomment-699467732">comment</a> buried within a sea of comments and issues all around the internet</p>
<h2 id="heading-unable-to-launch-ubuntu-post-installation">Unable to launch Ubuntu post installation</h2>
<p>If you run the following command <code>Add-AppxPackage .\Ubuntu2204-221101.AppxBundle</code> to install the Ubuntu distribution but</p>
<ul>
<li><p>it did not show any installed distro after running <code>wsl -l -v</code></p>
<pre><code class="lang-bash">  PS C:\wsl&gt; wsl -l -v
  Windows Subsystem <span class="hljs-keyword">for</span> Linux has no installed distributions.
  Distributions can be installed by visiting the Microsoft Store:
  https://aka.ms/wslstore
</code></pre>
</li>
<li><p>You cannot launch it via the Start Menu</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670068136460/719452b5-b78f-4f25-acc0-072f3414648c.gif" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>I hope this will help to solve your issue.</p>
<p>So what happened? I believe this has to do with permission somehow due to manual installation. If we look at the windows event logs, we can find the following error</p>
<pre><code class="lang-bash">0x800704CF: Cannot create the process <span class="hljs-keyword">for</span> package CanonicalGroupLimited.Ubuntu_2204.1.7.0_x64__79rhkp1fndgsc because an error was encountered <span class="hljs-keyword">while</span> preparing <span class="hljs-keyword">for</span> activation.
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670068646546/e203eaff-ad4d-44ee-ad2f-e2e59b755256.png" alt class="image--center mx-auto" /></p>
<p>And if you attempt to launch via the installer file, you will encounter the following error</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670068757321/0e18edf8-62fd-4a52-a442-312801014ba7.gif" alt class="image--center mx-auto" /></p>
<p>After some google searches, I finally landed on a workaround mentioned <a target="_blank" href="https://github.com/microsoft/WSL/issues/3020#issuecomment-604589190">here</a> and <a target="_blank" href="https://github.com/microsoft/WSL/issues/2577#issuecomment-344583203">here</a> which is to copy the ubuntu directory to another location (i.e. <code>C:\</code>)</p>
<p>However, if you attempt to access <code>C:\Program Files\WindowsApp</code>, you will encounter yet another error</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670069143816/731f9f56-c81c-4646-b985-c1e02b55d16c.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670069166815/072686d6-3c7b-4bb8-80a3-34eac85804a8.png" alt class="image--center mx-auto" /></p>
<p>Follow the <a target="_blank" href="https://www.makeuseof.com/windows-access-windowsapps-folder/">instruction</a> listed under <code>1. How to Access WindowsApps via File Explorer</code> should suffice. Once you gain access to the <code>WindowsApp</code> directory, copy <code>CanonicalGroupLimited.Ubuntu_2204.1.7.0_x64__79rhkp1fndgsc</code> directory to <code>C:\</code> (or any other location of your choice)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670069674451/60640fd6-96da-43d9-9d42-5a46f7e02556.gif" alt class="image--center mx-auto" /></p>
<blockquote>
<p>Remember to head back to <a class="post-section-overview" href="#heading-install-ubuntu-2204-lts">installing-ubuntu-2204-lts</a> if you came from there and continue the rest of the instruction</p>
</blockquote>
<h2 id="heading-missing-wsl-optional-component">Missing WSL optional component</h2>
<p>If you attempt to launch WSL right after installation, and you may face the following error</p>
<pre><code class="lang-bash">This application requires the Windows Subsystem <span class="hljs-keyword">for</span> Linux Optional Component.
The system may need to be restarted so the changes can take effect.
Press any key to <span class="hljs-built_in">continue</span>...
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670063660051/1c462c23-b2f1-4178-9ad5-a70ff222a15f.png" alt class="image--center mx-auto" /></p>
<p>That means exactly what the error message said, where the WSL optional component is not enabled yet. So make sure you follow the instruction listed <a class="post-section-overview" href="#heading-windows-features">here</a> to enable the WSL component.</p>
<h2 id="heading-wsl-2-kernel-file-is-not-found">WSL 2 Kernel file is not found</h2>
<p>If you ran <code>wsl --status</code> and you get the following message</p>
<pre><code class="lang-bash">Default Version: 2

The Windows Subsystem <span class="hljs-keyword">for</span> Linux kernel can be manually updated with <span class="hljs-string">'wsl --update'</span>, but automatic updates cannot occur due to your system settings. To receive automatic kernel updates, please <span class="hljs-built_in">enable</span> the Windows Update setting: <span class="hljs-string">'Receive updates for other Microsoft products when you update Windows'</span>. For more information please visit https://aka.ms/wsl2kernel.

The WSL 2 kernel file is not found. To update or restore the kernel please run <span class="hljs-string">'wsl.exe --update'</span>
</code></pre>
<p>Double-click on <code>wsl_update_x64.msi</code> to update the kernel and then run <code>wsl --status</code> again and you should see the following now.</p>
<p>Notice the kernel version is now showing as <code>5.10.16</code></p>
<pre><code class="lang-bash">Default Version: 2

Windows Subsystem <span class="hljs-keyword">for</span> Linux was last updated on 3/12/2022
The Windows Subsystem <span class="hljs-keyword">for</span> Linux kernel can be manually updated with <span class="hljs-string">'wsl --update'</span>, but automatic updates cannot occur due to your system settings.
To receive automatic kernel updates, please <span class="hljs-built_in">enable</span> the Windows Update setting: <span class="hljs-string">'Receive updates for other Microsoft products when you update Windows'</span>.
For more information please visit https://aka.ms/wsl2kernel.

Kernel version: 5.10.16
</code></pre>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/windows/wsl/troubleshooting#installation-issues">WSL Troubleshooting Guide</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/windows/wsl/install-manual">WSL Manual Install</a></p>
</li>
<li><p><a target="_blank" href="https://www.nakivo.com/blog/vmware-nested-virtualization-explained-use-cases-and-tutorial/">VMWare nested virtualization explained</a></p>
</li>
<li><p><a target="_blank" href="https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html">VMWare now supports Hyper-V mode</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Installing oh-my-posh using winget]]></title><description><![CDATA[This is a follow-up blog post to a previous article on enhance your developer experience with Windows Terminal and PowerShell, specifically with regard to…]]></description><link>https://bwgjoseph.com/installing-oh-my-posh-using-winget</link><guid isPermaLink="true">https://bwgjoseph.com/installing-oh-my-posh-using-winget</guid><category><![CDATA[windows terminal]]></category><category><![CDATA[Developer Tools]]></category><category><![CDATA[Powershell]]></category><category><![CDATA[oh-my-posh]]></category><category><![CDATA[shell]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 26 Nov 2022 07:09:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1669446379892/hOEArjfhc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a follow-up blog post to a previous article on <a target="_blank" href="https://bwgjoseph.com/enhance-your-developer-experience-with-windows-terminal-and-powershell">enhance your developer experience with Windows Terminal and PowerShell</a>, specifically with regard to the setup of <code>oh-my-posh</code></p>
<p>Based on the <a target="_blank" href="https://ohmyposh.dev/docs/migrating#install-oh-my-posh">website</a>, the recommended way now is to use <a target="_blank" href="https://learn.microsoft.com/en-us/windows/package-manager/winget/">winget</a> to install <code>oh-my-posh</code></p>
<blockquote>
<p><code>winget</code> is a <strong>Windows Package Manager</strong> to enables users to discover, install, upgrade, remove and configure applications on Windows 10 and Windows 11 computers</p>
</blockquote>
<h1 id="heading-uninstall">Uninstall</h1>
<p>First, let's get rid of the old configuration and setup done previously</p>
<ul>
<li><p>Launch <code>Powershell</code></p>
</li>
<li><p>Run <code>Remove-Item $env:POSH_PATH -Force -Recurse</code></p>
</li>
<li><p>Run <code>Uninstall-Module oh-my-posh -AllVersions</code></p>
</li>
<li><p>Run <code>code $PROFILE</code></p>
<ul>
<li>This will launch your PowerShell profile on <code>VSCode</code></li>
</ul>
</li>
<li><p>Remove the following from your profile</p>
<ul>
<li><p><code>Import-Module oh-my-posh</code> line</p>
</li>
<li><p><code>Set-PoshPrompt night-owl</code></p>
<ul>
<li>Or any profile you have defined previously, in my case, it was <code>night-owl</code></li>
</ul>
</li>
</ul>
</li>
<li><p>Remove <code>%USERPROFILE%\.oh-my-posh</code> from your <code>PATH</code> environment variable</p>
</li>
</ul>
<p>Now, re-launch your PowerShell, it should look plain now</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668095660572/fzBGM7hrZ.png" alt="image.png" /></p>
<hr />
<h1 id="heading-installation">Installation</h1>
<p>Now that we have removed it, we need to set up <code>oh-my-posh</code> again</p>
<ul>
<li><p>Launch <code>PowerShell</code></p>
</li>
<li><p>Run <code>winget install JanDeDobbeleer.OhMyPosh -s winget</code></p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668095755658/ZDrmC9_j5.png" alt="image.png" /></p>
<ul>
<li><p>Restart <code>PowerShell</code> terminal</p>
</li>
<li><p>Run <code>oh-my-post --version</code></p>
<ul>
<li>Your version will differ from mine, depending on when you install it</li>
</ul>
</li>
</ul>
<pre><code class="lang-plaintext">PS C:\Users\Joseph&gt; oh-my-posh --version
12.13.1
</code></pre>
<p>Now that <code>oh-my-posh</code> is installed, we have to instruct <code>PowerShell</code> to use it</p>
<ul>
<li><p>Run <code>code $PROFILE</code></p>
</li>
<li><p>Add <code>oh-my-posh init pwsh | Invoke-Expression</code> to the last line of your $PROFILE</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669445656023/fVaJSckCK.png" alt="image.png" /></p>
<p>What about setting up the theme? It's quite straight forward, upon installation of <code>oh-my-posh</code>, it also set up an environment variable <code>POSH_THEMES_PATH</code> to point to the location of the themes.</p>
<ul>
<li>Replace <code>oh-my-posh init pwsh | Invoke-Expression</code> with <code>oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\night-owl.omp.json" | Invoke-Expression</code> in your $PROFILE</li>
</ul>
<blockquote>
<p>Replace <code>night-owl.omp.json</code> with your preferred theme</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669445734025/JHwmtYYtY.png" alt="image.png" />
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669445845083/6M0UI1Z9R.png" alt="image.png" /></p>
<p>Your theme is now back!</p>
<h2 id="heading-bashrc">bashrc</h2>
<p>If you have set for <code>.bashrc</code> previously, you might need to update the path</p>
<pre><code class="lang-bash">// from
<span class="hljs-built_in">eval</span> <span class="hljs-string">"<span class="hljs-subst">$(oh-my-posh --init --shell bash --config ~/.oh-my-posh/themes/night-owl.omp.json)</span>"</span>

// to
<span class="hljs-built_in">eval</span> <span class="hljs-string">"<span class="hljs-subst">$(oh-my-posh --init --shell bash --config ~/AppData/Local/Programs/oh-my-posh/themes/night-owl.omp.json)</span>"</span>
</code></pre>
<h2 id="heading-wsl">WSL</h2>
<p>If you have set for WSL (previously)</p>
<ul>
<li><p>Launch your terminal</p>
</li>
<li><p>Run</p>
</li>
</ul>
<pre><code class="lang-plaintext">sudo wget https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/posh-linux-amd64 -O /usr/local/bin/oh-my-posh
sudo chmod +x /usr/local/bin/oh-my-posh
</code></pre>
<p>And if you are using <code>zsh</code> within your <code>WSL</code>, remember to update your <code>.zshrc</code> config as well</p>
<h3 id="heading-zshrc">zshrc</h3>
<pre><code class="lang-plaintext"># use vim if you like
nano ~/.zshrc
# place this at the end of the file
# we are referencing to our theme in Windows path
# switch the username to yours
eval "$(oh-my-posh --init --shell zsh --config '/mnt/c/Users/Joseph/AppData/Local/Programs/oh-my-posh/themes/night-owl.omp.json')"
// Reload profile
exec zsh
</code></pre>
<p>If you face this error <code>Error: unknown flag: --millis</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668097015505/PHuP2Fbjr.png" alt="image.png" /></p>
<p>This is likely that your configuration is wrong, ensure you point to the correct path in your shell (e.g zsh) config</p>
<p>That should be it. Enjoy your newly setup terminal!</p>
]]></content:encoded></item><item><title><![CDATA[[Docusaurus] How to enable showLastUpdate feature when deployed via Gitlab CI]]></title><description><![CDATA[I had trouble getting showLastUpdateAuthor and showLastUpdateTime to display in production build when deploying through Gitlab CI. Before I show you how to…]]></description><link>https://bwgjoseph.com/docusaurus-how-to-enable-showlastupdate-feature-when-deployed-via-gitlab-ci</link><guid isPermaLink="true">https://bwgjoseph.com/docusaurus-how-to-enable-showlastupdate-feature-when-deployed-via-gitlab-ci</guid><category><![CDATA[docusaurus]]></category><category><![CDATA[documentation]]></category><category><![CDATA[GitLab-CI]]></category><category><![CDATA[GitLab]]></category><category><![CDATA[Git]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Sat, 05 Nov 2022 08:52:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667638183594/D40u-fAkz.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-context">Context</h1>
<p>I had trouble getting <a target="_blank" href="https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-docs#showLastUpdateAuthor">showLastUpdateAuthor</a> and <a target="_blank" href="https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-docs#showLastUpdateTime">showLastUpdateTime</a> to display in production build when deploying through <code>Gitlab CI</code>.</p>
<p>Before I show you how to fix it, let's see what this feature is about</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667634489223/PBjkzGB_B.png" alt="image.png" /></p>
<p>As shown in the image (circled) above, at the bottom of each page, it will reflect when was the document last updated and by whom. While this feature is not absolutely necessary, it is useful to know this piece of information.</p>
<h1 id="heading-setup">Setup</h1>
<p>The setup is pretty straight-forward if you are using the defaults for the most part. You can look at the <a target="_blank" href="https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-docs">detailed instruction</a> stated on the website.</p>
<p>Here's the TLDR version, in your <code>docusaurus.config.js</code>, navigate to <code>presets</code> config and configure like such</p>
<pre><code class="lang-json">presets: [
    [
      '@docusaurus/preset-classic',
      {
        docs: {
          sidebarPath: 'sidebars.js',
          editUrl: 'https:<span class="hljs-comment">//gitlab.com/bwgjoseph/etp-docs/-/edit/main/',</span>
          showLastUpdateAuthor: <span class="hljs-literal">true</span>,
          showLastUpdateTime: <span class="hljs-literal">true</span>
        }
      }
    ]
  ],
</code></pre>
<p>That's actually all you have to do to get it working, but note that this does not (really) work in development mode. In development mode, it will be simulated.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667635299347/hBs_w18Ki.png" alt="image.png" /></p>
<p>If you wish to see the actual value, you have to build, and serve the content out locally.</p>
<pre><code class="lang-java">yarn build
yarn serve
</code></pre>
<h1 id="heading-problem">Problem</h1>
<h2 id="heading-what-happened">What happened?</h2>
<p>I'm deploying my docs using <code>Gitlab Pages</code> via <code>Gitlab CI</code>, and it wouldn't display the user and timestamp in the production build. There was no obvious error (the entire pipeline actually pass), until I look closer to my <code>Gitlab CI logs</code> which show this</p>
<pre><code class="lang-java">$ yarn build
yarn run v1.<span class="hljs-number">22.18</span>
$ docusaurus build
[INFO] [en] Creating an optimized production build...
[WARNING] Sorry, the docs plugin last update options require Git.
Browserslist: caniuse-lite is outdated. Please run:
  npx browserslist<span class="hljs-meta">@latest</span> --update-db
  Why you should <span class="hljs-keyword">do</span> it regularly: https:<span class="hljs-comment">//github.com/browserslist/browserslist#browsers-data-updating</span>
[info] [webpackbar] Compiling Client
[info] [webpackbar] Compiling Server
[success] [webpackbar] Client: Compiled successfully in <span class="hljs-number">57.72</span>s
[success] [webpackbar] Server: Compiled successfully in <span class="hljs-number">1.03</span>m
[SUCCESS] Generated <span class="hljs-keyword">static</span> files in <span class="hljs-string">"build"</span>.
[INFO] Use `npm run serve` command to test your build locally.
Done in <span class="hljs-number">97.92</span>s.
</code></pre>
<p>There was a warning message at Line 5, indicating <code>Sorry, the docs plugin last update options require Git</code> which I don't quite understand at first. Some thoughts that ran through my mind were, "Why wouldn't there be Git? If there isn't, then how did the pipeline clone the repository?"</p>
<h2 id="heading-understanding-the-cause">Understanding the cause</h2>
<p>To explain this, let's zoom into the pipeline stage that is responsible to build the artifact.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">build:</span>
  <span class="hljs-attr">stage:</span> <span class="hljs-string">build</span>
  <span class="hljs-attr">image:</span> <span class="hljs-string">node:16.15.0-alpine</span>
  <span class="hljs-attr">script:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">yarn</span> <span class="hljs-string">build</span>
</code></pre>
<p>So in the <code>build</code> stage, the command <code>yarn build</code> will use <code>git</code> to generate the <code>lastUpdate</code> information. However, the image that I used is <code>node:16.15.0-alpine</code> which does not come with <code>git</code> installed.</p>
<h2 id="heading-resolution">Resolution</h2>
<blockquote>
<p>15/2/2023 Update: Alternatively, switch to use non-alpine node image and it will work without manually installing git. If image size is a concern, then using the solution below might be better for you</p>
</blockquote>
<p>Hence, to resolve it, all I had to do was to install <code>git</code> via the <code>before_script</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">build:</span>
  <span class="hljs-attr">stage:</span> <span class="hljs-string">build</span>
  <span class="hljs-attr">image:</span> <span class="hljs-string">node:16.15.0-alpine</span>
  <span class="hljs-attr">before_script:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">apk</span> <span class="hljs-string">update</span> <span class="hljs-string">&amp;&amp;</span> <span class="hljs-string">apk</span> <span class="hljs-string">--no-cache</span> <span class="hljs-string">add</span> <span class="hljs-string">git</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">git</span> <span class="hljs-string">--version</span>
  <span class="hljs-attr">script:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">yarn</span> <span class="hljs-string">build</span>
</code></pre>
<p>Once I fixed this, and ran the pipeline again, we can see the following in the logs</p>
<pre><code class="lang-java">$ apk update &amp;&amp; apk --no-cache add git
fetch https:<span class="hljs-comment">//dl-cdn.alpinelinux.org/alpine/v3.15/main/x86_64/APKINDEX.tar.gz</span>
fetch https:<span class="hljs-comment">//dl-cdn.alpinelinux.org/alpine/v3.15/community/x86_64/APKINDEX.tar.gz</span>
<span class="hljs-comment">// omitted</span>
(<span class="hljs-number">7</span>/<span class="hljs-number">7</span>) <span class="hljs-function">Installing <span class="hljs-title">git</span> <span class="hljs-params">(<span class="hljs-number">2.34</span><span class="hljs-number">.5</span>-r0)</span>
Executing busybox-1.34.1-r5.trigger
Executing ca-certificates-20220614-r0.trigger
OK: 21 MiB in 23 packages
$ git --version
git version 2.34.5</span>
</code></pre>
<p>And viola! The production build will now display the last updated timestamp and author information.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>While the setup is straight-forward, to get it working in production which is deployed via <code>Gitlab CI</code>, you need some working knowledge of how the pipeline is configured and run.</p>
<p>Hope this helps someone else that face this issue when deploying via <code>Gitlab CI</code> as I was not able to find any information.</p>
<p>You will probably not face this issue if you deploy this manually.</p>
]]></content:encoded></item><item><title><![CDATA[Default mapping behavior for Spring Data MongoDB]]></title><description><![CDATA[If you have used Spring Data MongoDB, have you ever thought of what exactly is the default mapping behavior from MongoDB Document to Java POJO? What do I…]]></description><link>https://bwgjoseph.com/default-mapping-behavior-for-spring-data-mongodb</link><guid isPermaLink="true">https://bwgjoseph.com/default-mapping-behavior-for-spring-data-mongodb</guid><category><![CDATA[Java]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[spring data]]></category><dc:creator><![CDATA[Joseph Gan]]></dc:creator><pubDate>Wed, 02 Nov 2022 15:40:16 GMT</pubDate><content:encoded><![CDATA[<p>If you have used <code>Spring Data MongoDB</code>, have you ever thought of what exactly is the default mapping behavior from <code>MongoDB Document</code> to <code>Java POJO</code>? What do I mean by that?</p>
<p>Imagine you have the following Java POJO</p>
<pre><code class="lang-java"><span class="hljs-meta">@Getter</span>
<span class="hljs-meta">@Builder</span>
<span class="hljs-meta">@ToString</span>
<span class="hljs-meta">@TypeAlias("person")</span>
<span class="hljs-meta">@Document("person")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;
    <span class="hljs-keyword">private</span> Integer height;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> isAdult;
    <span class="hljs-keyword">private</span> Address address;
    <span class="hljs-keyword">private</span> List&lt;String&gt; hobbies;
    <span class="hljs-keyword">private</span> List&lt;Address&gt; addresses;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Address</span><span class="hljs-params">(String street, String postalCode)</span> </span>{}
</code></pre>
<ul>
<li>Used <a target="_blank" href="https://projectlombok.org/">lombok</a> <code>Getter, Builder, and ToString</code> annotation</li>
<li>Note that I have purposely defined the POJO with various <code>primitive, and non-primitive (reference)</code> data types</li>
</ul>
<p>What happens when I save the following object using <code>repository.save(person)</code>, and some of the values are not set?</p>
<p>And if we flip the scenario, imagine you have the following <code>MongoDB Document</code></p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_id"</span>: <span class="hljs-string">"63563b8cc056726c1d30c1c3"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"hello"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-attr">"height"</span>: <span class="hljs-number">177</span>,
    <span class="hljs-attr">"isAdult"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"address"</span>: {
        <span class="hljs-attr">"street"</span>: <span class="hljs-string">"18 New Road"</span>,
        <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"654321"</span>
    },
    <span class="hljs-attr">"hobbies"</span>: [<span class="hljs-string">"soccer"</span>, <span class="hljs-string">"volleyball"</span>],
    <span class="hljs-attr">"addresses"</span>: [
        {
            <span class="hljs-attr">"street"</span>: <span class="hljs-string">"17 Old Road"</span>,
            <span class="hljs-attr">"postalCode"</span>: <span class="hljs-string">"123456"</span>
        }
    ]
}
</code></pre>
<p>What happens when I retrieve the following document from <code>MongoDB</code> using <code>repository.findById("63563b8cc056726c1d30c1c3")</code>, and some of the fields does not exist?</p>
<p>In this blog post, I will focus on the default behavior without digging into the internals, and discuss what it means and what I think the default value should be set as.</p>
<h1 id="heading-assumption">Assumption</h1>
<p>You have a local instance of <code>MongoDB</code> installed, with a username as <code>root</code> and password as <code>password</code></p>
<h1 id="heading-setup">Setup</h1>
<p>For the setup, it will be quite simple and straight-forward. Aside from the <code>POJOs</code> defined above, we only require to configure the <code>Repository</code> and <code>Tests</code> class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PersonRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">MongoRepository</span>&lt;<span class="hljs-title">Person</span>, <span class="hljs-title">String</span>&gt; </span>{

}
</code></pre>
<pre><code class="lang-java"><span class="hljs-meta">@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonRepositoryCrudTests</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> PersonRepository repository;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-meta">@Order(1)</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">createEmptyObjectWithBuilder</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// to fill up later....</span>
    }
}
</code></pre>
<blockquote>
<p>Excluded <code>EmbeddedMongoAutoConfiguration</code> as I'm not using embedded <code>MongoDB</code></p>
</blockquote>
<h1 id="heading-tests">Tests</h1>
<h2 id="heading-empty-null-object">Empty / Null Object</h2>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">createEmptyObjectWithBuilder</span><span class="hljs-params">()</span> </span>{
    Person toCreate = Person.builder().name(<span class="hljs-keyword">null</span>).build();
    Person created = <span class="hljs-keyword">this</span>.repository.save(toCreate);

    Assertions.assertThat(created.getName()).isNull();
    Assertions.assertThat(created.getAge()).isZero();
    Assertions.assertThat(created.getHeight()).isZero();
    Assertions.assertThat(created.isAdult()).isFalse();
    Assertions.assertThat(created.getAddress()).isNull();
    Assertions.assertThat(created.getHobbies()).isEmpty();
    Assertions.assertThat(created.getAddresses()).isEmpty();

    log.info(<span class="hljs-string">"{}"</span>, created);
}
</code></pre>
<blockquote>
<p>I'm using <code>@Builder</code> pattern from <code>Lombok</code> to create the object, <code>Assertions</code> from <code>AssertJ</code> and <code>@Slf4j</code> annotation from <code>Lombok</code> to call the <code>log</code> statement</p>
</blockquote>
<p>The output is</p>
<pre><code class="lang-json"><span class="hljs-comment">// document in mongodb</span>
{
    <span class="hljs-attr">"_id"</span> : ObjectId(<span class="hljs-string">"63564997e88e844484c40d97"</span>),
    <span class="hljs-attr">"age"</span> : NumberInt(<span class="hljs-number">0</span>),
    <span class="hljs-attr">"isAdult"</span> : <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"_class"</span> : <span class="hljs-string">"person"</span>
}
</code></pre>
<pre><code><span class="hljs-comment">// log output</span>
Person(id=<span class="hljs-number">6356996013</span>bcce4608b5c0b5, name=<span class="hljs-literal">null</span>, age=<span class="hljs-number">0</span>, height=<span class="hljs-literal">null</span>, isAdult=<span class="hljs-literal">false</span>, address=<span class="hljs-literal">null</span>, hobbies=<span class="hljs-literal">null</span>, addresses=<span class="hljs-literal">null</span>)
</code></pre><p>What do we learn or see from this simple test case?</p>
<p>In terms of saving the document to <code>MongoDB</code></p>
<ul>
<li>Any field that is not defined (or null) <strong>AND</strong> is a <strong>non-primitive</strong> field, <strong>will not</strong> have a corresponding field in the actual created document</li>
<li>Any field that is not defined <strong>AND</strong> is a <strong>primitive</strong> field, <strong>will have</strong> a corresponding field in the actual created document and set to its default value (i.e 0 for int, false for boolean and so on)</li>
</ul>
<p>In terms of getting the document from <code>MongoDB</code></p>
<ul>
<li>Any field that does not exist (or null) <strong>AND</strong> is a <strong>non-primitive</strong> field, will be set as <code>null</code></li>
<li>Any field that does not exist <strong>AND</strong> is a <strong>primitive</strong> field, will be set to its default value (i.e 0 for int, false for boolean and so on)</li>
</ul>
<h1 id="heading-impact">Impact</h1>
<p>What does it mean to not have a field exist in the document, and for a field to be null as a default value?</p>
<p>In <code>MongoDB</code>, it is perfectly fine and acceptable where the field does not exist for a certain document, and that's the beauty of <code>NoSQL</code> with the <code>schemaless</code> design.</p>
<p>In <code>weakly typed language</code> such as <code>javascript</code>, it would be fine too (I suspect). However, for a <code>strongly typed language</code> such as <code>Java</code>, this might be a big issue in my opinion, if not carefully handled. Why is that so? In short, I would have to be extra careful whenever I'm using the field(s) due to possiblilty of encountering <code>NullPointerException</code>.</p>
<h1 id="heading-recommendation">Recommendation</h1>
<h2 id="heading-sensible-defaults">Sensible Defaults</h2>
<p>In order to ensure that the fields are not <code>null</code> by default, we need to define a default value, and it largely depends on your use-case but here are some sensible default that should apply to most use-case.</p>
<h3 id="heading-primitive">Primitive</h3>
<p>Technically, you don't have to assign any default to Java primitive value, as there already is a default. Unless you want the default to be different, you don't have any do anything.</p>
<h3 id="heading-non-primitive-reference">Non-Primitive (Reference)</h3>
<p>In the Person POJO, the default for the various data types should be:</p>
<ul>
<li><code>String</code>: empty string (or whatever that better suit your use-case)</li>
<li><code>Integer</code>: 0 (or whatever that better suit your use-case)</li>
<li><code>Address</code>: null (or whatever that better suit your use-case)</li>
<li><code>List&lt;String&gt;</code>: empty array</li>
<li><code>List&lt;Address&gt;</code>: empty array</li>
</ul>
<p>It is particularly challenging to determine the default if it's a class reference data type (i.e Address), because assigning <code>null</code> would incur possible <code>NullPointerException</code> but most of the time, there wouldn't be a sensible default for a class reference data type field.</p>
<h2 id="heading-use-lombok-builderdefault">Use Lombok Builder.Default</h2>
<p>Since we are already using <code>Lombok</code> (&gt;= v1.16.16), then using <a target="_blank" href="https://projectlombok.org/features/Builder">Lombok Builder.Default</a> is a possible solution, where you can specify the default value if not set.</p>
<p>Let's update our <code>Person POJO</code> class to the following</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-meta">@Builder</span>.Default
    <span class="hljs-keyword">private</span> String name = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;
    <span class="hljs-meta">@Builder</span>.Default
    <span class="hljs-keyword">private</span> Integer height = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> isAdult;
    <span class="hljs-meta">@Builder</span>.Default
    <span class="hljs-keyword">private</span> List&lt;String&gt; hobbies = List.of();
    <span class="hljs-meta">@Builder</span>.Default
    <span class="hljs-keyword">private</span> List&lt;Address&gt; addresses = List.of();
}
</code></pre>
<p>Running back the previous test will produce the following output</p>
<pre><code>Person(id=<span class="hljs-number">63565798338016237</span>d70f0b0, name=<span class="hljs-literal">null</span>, age=<span class="hljs-number">0</span>, height=<span class="hljs-number">0</span>, isAdult=<span class="hljs-literal">false</span>, hobbies=[], addresses=[])
</code></pre><p>Notice that except for <code>name</code> which is still <code>null</code>, the rest of the fields are initialized with a default value. The reason for <code>name</code> being <code>null</code>, is that it was explicitly defined as <code>null</code> during the object creation in the test case.</p>
<p>The downside to this is that this will only be true if you are using the <code>Builder</code> to construct your object. If you were to construct the object via other means (e.g <code>new Person()</code>), this would not have applied. And also to note some of the current pitfall when using <code>Builder.Default</code> with explicit constructor, which is currently tracked at <a target="_blank" href="https://github.com/projectlombok/lombok/issues/2340">lombok-github-issue</a>.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>We tested the default behavior for the mapping between Java POJO and MongoDB document when using Spring Data MongoDB, and understand the pitfall, and how we might overcome it.</p>
<p>However, please proceed with caution, as this is a very contrived example which does not take many other things into consideration such as constructing the object via default or explicit constructor.</p>
<p>If there is one thing to take-away from this, is to know what is the default behavior of the mapping, and that allowing the default value to be null should be avoided as much as possible.</p>
<h1 id="heading-source-code">Source Code</h1>
<p>As usual, full source code is available in <a target="_blank" href="https://github.com/bwgjoseph/tutorials/tree/main/spring-boot-mongodb-default-mapping">GitHub</a></p>
]]></content:encoded></item></channel></rss>