Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 40 ยท Projects

Project: CI for a Java Application

Build a complete Jenkins CI pipeline for a Maven project: build, JUnit reports, archived jar, multibranch setup and a quality gate, with a runnable stage simulator.

In this project you assemble a realistic continuous-integration pipeline for a Java application built with Maven. It compiles the code, runs the tests, publishes the test report, archives the jar, runs on every branch and pull request, and stops the build when the code quality is not good enough. Nothing here is new; the point is to see the pieces working together.

The real Jenkins, Maven and SonarQube cannot run on this site, so the Jenkinsfile and commands are read-only. A Node stand-in at the end runs the same stages as a simulation, so you can see the order, the early exit on failure, and the effect of the quality gate.

The pipeline we will build

Build Compile with Maven.
Test Run unit tests, publish the report.
Package Archive the jar with a fingerprint.
Quality gate Fail if the code is not good enough.

Every branch and pull request gets the same checks.

1 / 2

The project and its goals

Assume a Maven project with a standard layout: pom.xml at the root, code in src/main/java, tests in src/test/java. It lives in Git, and the pipeline file Jenkinsfile sits in the root next to pom.xml.

Goals, in order of importance:

  1. Every push and every pull request is built and tested automatically.
  2. Test results are visible in Jenkins, with a trend across builds.
  3. A passing build produces an archived jar that can be deployed later.
  4. Code that fails the quality gate does not get merged.
  5. The pipeline is the same for all branches (a multibranch job).

Prerequisites on the controller

You need these plugins (see Plugins): Pipeline, Git, JUnit (usually pre-installed), Pipeline Maven or just the Maven tool configuration, and, if you use SonarQube, the SonarQube Scanner plugin. An agent labeled maven should have a JDK installed, or you can use a Docker agent image that contains both Java and Maven (see Docker Agents and Building Images).

If your project includes the Maven Wrapper (mvnw), prefer it: the build then uses the Maven version the project pins, and the agent does not need Maven installed. Dependency downloads are cached in ~/.m2 on a long-lived agent, which makes repeated builds much faster (see Building Java, Node and Python Projects).

The Jenkinsfile

This is the full pipeline (read-only). Read it once, then we will go through the decisions.

GROOVY
pipeline {
  agent { label 'maven' }

  options {
    timeout(time: 20, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
    disableConcurrentBuilds(abortPrevious: true)
  }

  tools {
    jdk 'jdk21'
  }

  stages {
    stage('Build') {
      steps {
        sh './mvnw -B -ntp -DskipTests clean compile'
      }
    }

    stage('Test') {
      steps {
        sh './mvnw -B -ntp test'
      }
      post {
        always {
          junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
        }
      }
    }

    stage('Package') {
      steps {
        sh './mvnw -B -ntp -DskipTests package'
      }
      post {
        success {
          archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
        }
      }
    }

    stage('Quality gate') {
      when { anyOf { branch 'main'; changeRequest() } }
      steps {
        withSonarQubeEnv('sonarqube') {
          sh './mvnw -B -ntp sonar:sonar'
        }
        timeout(time: 10, unit: 'MINUTES') {
          waitForQualityGate abortPipeline: true
        }
      }
    }
  }

  post {
    failure {
      echo "Build failed: ${env.BUILD_URL}"
    }
    cleanup {
      cleanWs()
    }
  }
}

Why it is built this way

  • -B (batch mode) removes the interactive progress bars from logs, and -ntp hides the noisy download messages. Both make console output readable.
  • timeout at the top and around the gate stops a stuck build from holding an executor forever. See Backup, Monitoring and Troubleshooting.
  • buildDiscarder keeps the last 30 builds, and artifacts for only the last 5, so disk usage stays bounded.
  • disableConcurrentBuilds(abortPrevious: true) cancels an older running build of the same branch when a new commit arrives; nobody needs the result for outdated code.
  • Splitting Build, Test and Package gives clear failure points in the stage view: a red Test box means compile worked and a test failed.
  • The junit step is in post { always } of the test stage, so the report is published even when tests fail. Without that, a failing run would show no details. If tests fail, the build becomes UNSTABLE or FAILURE depending on the Maven setting; with plain mvn test, Maven exits non-zero on failing tests, which stops the pipeline, and the report is still recorded by the always block.
  • archiveArtifacts with fingerprint: true stores the jar and records its checksum, so you can later find which builds produced or consumed a given file (see Artifacts, Stash and Fingerprints).
  • post { cleanup { cleanWs() } } clears the workspace at the very end, so leftovers cannot affect the next run. It needs the Workspace Cleanup plugin.

Pull requests and branches

Create this as a Multibranch Pipeline job pointing at your repository (see Multibranch Pipelines and Pull Requests). Jenkins scans the repository, finds every branch and pull request containing a Jenkinsfile, and creates a sub-job for each. With a webhook from your Git host (see Triggers), a new push starts a build within seconds. The Git host then shows the Jenkins result as a status check on the pull request, and you can make that check required in the branch protection rules.

The quality gate

SonarQube (or a similar analyzer) inspects the code for bugs, vulnerabilities, duplicated code and coverage, then compares the numbers with a quality gate you defined, for example "coverage on new code at least 80%, no new critical issues". The scanner uploads the analysis, and waitForQualityGate pauses until the server reports the verdict, which comes back through a webhook configured in SonarQube. With abortPipeline: true, a failed gate fails the build.

The gate runs only for main and pull requests, using the when expression, because analyzing every feature branch is often unnecessary. The quality gate configuration (thresholds) belongs to the analysis server, not to the Jenkinsfile; the pipeline only enforces the result. If you do not use SonarQube, the same idea works with a coverage tool or static analyzer that fails the build below a threshold (see Tests, JUnit Reports and Quality Gates).

Reading the result

After a build, the build page shows the stage view, a Test Result page with a trend graph, the list of archived artifacts, and the console output. If a test fails, click it in the Test Result page to see its message and stack trace. A test that fails in some builds and passes in others is flaky; fix or quarantine it, because teams stop trusting a pipeline that cries wolf.

A stand-in stage runner

The simulator below runs the same four stages with fake results. Each stage is a function that can pass or fail. The runner stops at the first failure (like a pipeline), still publishes the test report in always, and runs cleanup at the end. Change the scenario objects to see the different outcomes. It is a model of the control flow, not Maven or Jenkins.

Node.js A stand-in runner for the Java CI stages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare the four runs. Build 18 passes everything. Build 19 passes even though coverage is low, because the gate does not run on feature branches (a design choice you can change). Build 20 fails in Test but the report is still published, and Package never runs. Build 21 is stopped by the quality gate after the jar was already archived; the archive exists, but the build is red, so nobody should deploy it.

Extending the project

Once this works, natural next steps are:

Commit the Jenkinsfile in the same pull request that changes the build. Then the pipeline and the code always match, and an old branch builds with the pipeline it was written for.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the junit step placed in 'post { always }' of the Test stage?

    A failing build is exactly when you need the report. The always block runs whether the stage passed or failed.
  2. 2. What does 'waitForQualityGate abortPipeline: true' do?

    The step pauses until the analysis server reports its result, and with abortPipeline it aborts the pipeline on a failed gate.
  3. 3. What does a Multibranch Pipeline job give this project?

    Jenkins scans the repository and creates a sub-job per branch or pull request, all using the same Jenkinsfile.
  4. 4. Why use disableConcurrentBuilds(abortPrevious: true)?

    The older build tests code that is already outdated, so cancelling it saves executors and shortens feedback time.

Summary

  • A Java CI pipeline compiles, tests, packages and checks quality, with a clear stage for each step.
  • Use -B -ntp, timeouts, a build discarder and workspace cleanup to keep logs readable and disks healthy.
  • Publish JUnit results in post { always }, archive the jar with a fingerprint, and enforce a quality gate on main and pull requests.
  • A Multibranch Pipeline applies the same Jenkinsfile to every branch and pull request.
  • A failed gate or test makes the build red even if an artifact was produced, so never deploy from a red build.

Next, add containers to the mix in Project: Node App with Docker Build and Deploy.