Jenkins 2.0 pipeline +Git+ Maven + Nexus Repository 3.12 with Rest-Java-app

In one of my recent work i did demo a sample java-rest based application deployed using Jenkins 2.0 pipeline. To achieve this i created a one java-rest app and build it using maven. After building it, its getting uploaded on nexus repository. so start with first lets create a java rest service here is the sample code i had used

first service is HelloWorldService.java

package com.taa.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path(“/HelloWorld”)
public class HelloWorldService {
    @GET
    public Response getMsg(@PathParam(“param”) String msg) {
        String output = “Hello world: from TAA”;
        return Response.status(200).entity(output).build();
    }
}

Second Service is ByeByeService.java

package com.taa.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path(“/ByeWorld”)
public class ByeByeService {
    @GET
    public Response getMsg(@PathParam(“param”) String msg) {
        String output = “Bye world: from TAA”;
        return Response.status(200).entity(output).build();
    }
}
Once you have created the service we need to make sure it builds.  since in eclipse i created this project as Mavan-java project so it creates default pom.xml where i need to fill my dependency and Nexus repository urls. Here is the sample Pom.xml
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.naved.common</groupId>
    <artifactId>RESTfulExample</artifactId>
    <packaging>war</packaging>
    <version>1.5</version>
    <name>RESTfulExample Maven Webapp</name>
    <!– <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <layout>default</layout>
        </repository>
    </repositories> –>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19.4</version>
        </dependency>
    </dependencies>
    <distributionManagement>
        <repository>
            <id>releases</id>
            <name>Releases Repository</name>
            <url>
            http://nexusRepo:8081/repository/maven-releases/
            </url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>Snapshot Repository</name>
            <url>
            http://nexusRepo:8081/repository/maven-snapshots/
            </url>
        </snapshotRepository>
    </distributionManagement>
    <build>
        <finalName>RESTfulExample</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.7.0</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
             <artifactId>maven-clean-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <id>auto-clean</id>
                        <phase>initialize</phase>
                        <goals>
                        <goal>clean</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
             <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
                 <configuration>
<branchName>master</branchName>
<pushChanges>false</pushChanges>
<localCheckout>true</localCheckout>
                     <checkModificationExcludes>
                        <checkModificationExclude>pom.xml</checkModificationExclude>
                        <checkModificationExclude>**</checkModificationExclude>
                     </checkModificationExcludes>
</configuration>
</plugin>
        </plugins>
    </build>
     <scm>
<tag>HEAD</tag>
</scm>
</project>
You can log in through console/cmd line  and run “mvn clean install” to see its building the required artifact in  target directory. As it should now since this app is building successfully we need to make sure this become part of a successful CD pipeline so any changes build automatically.
You need to create a Jenkinsfile (name is your choice i prefer JenkinsFile) here is the sample JenkinsFile with each steps
pipeline {
Choose an agent
agent { label ‘build’ }
Setup an environment (its optional, ignore this part not relevant at this stage.)
environment {
       IMAGE = readMavenPom().getArtifactId()
       VERSION = readMavenPom().getVersion()
       BUILD_RELEASE_VERSION = readMavenPom().getVersion().replace(“-SNAPSHOT”, “.1.1”)
       IS_SNAPSHOT = readMavenPom().getVersion().endsWith(“-SNAPSHOT”)
       GIT_TAG_COMMIT = sh(script: ‘git describe –tags –always’, returnStdout: true).trim()
       NEW_VERSION = readMavenPom().getVersion()
}
Setup tools ( depends if you want to use specific one to be installed during jenkins kick off)
tools {
    jdk ‘jdk’
    maven ‘maven 3.5.3’
}
Pipeline contains multiple stages which gives you benefit i narrow down the failure .

stages{

I have called first stage as “Initialize” which is to initialize  path for home and path
Here i am using already installed
stage (‘Initialize’) {
   steps {
             sh ”’
              echo “PATH = ${PATH}”
             echo “M2_HOME = ${M2_HOME}”
            ”’
    }
}
After initialising its time to build
stage (‘Build’) {
steps {
   // some statement to print values
      echo ‘This is a minimal pipeline.’
      echo ” Project version is ${VERSION}”
      echo “Artifact id is ${IMAGE}”
      echo “Build release version is ${BUILD_RELEASE_VERSION}”
      echo ” is it snapshot ${IS_SNAPSHOT}”
      echo ” is GIT_TAG_COMMIT ${GIT_TAG_COMMIT}”
  // actual build command to and setting up version which to be build as.
sh ”’
    mvn versions:set -DnewVersion=1.0.2
    mvn clean install
”’
script{
      environment {
                               NEW_VERSION = readMavenPom().getVersion()
                               echo ” Project new version is ${NEW_VERSION}”
                             }
         }
    }
}
Deploy artifact into nexus repository, here i have more steps in which its manual on click of button on pipeline if user wants to deploy artifact into nexus repository.
If you just want to deploy remove everything from the steps except “mvn deploy”.
stage(‘Deploy To Integration’) {
         when { tag “release-*” }
             steps{
                       echo ‘start’
                       script{
                       def userWantToKeepCluster = {
                            try {
                                    timeout(time: 1, unit: ‘MINUTES’) {
                                    def keep = input message: ‘Deploy artifact ?’,
                                      parameters: [booleanParam(defaultValue: true, description:                                              ‘Make sure to destroy cluster manually after you done’, name: ‘Deploy artifact’)]
                                     return keep
                                 }
                                 } catch(e) {
                                     echo “Build Failed ::: User aborted build or its timed out”
                                      throw e
                                 }
                          }
                      def answer = userWantToKeepCluster()
                      echo “will keep cluster? $answer()”
                       if(answer)
                       {
                        echo “answer is $answer”
                        sh ”’
                               mvn deploy
                             ”’
                      }
                     else{
                              echo “Build is aborted, User does not want to deploy artifact”
                           }
                     }
                 echo ‘done’
              }
}
Close pipeline
  }
}
Here you can find the code
Now we need to configure jenkins pipeline.
Jenkins_pipelin_configure
now pipeline is ready for your execution as you click on build.
PipelineView
For any issue check console output, please feel free to raise any queries you have.

Published by sbcons

Sbcons has expertise in different areas of SDLC, provide solution, services and consultancy to all type of industry.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: