Promote API’s along with Application using Maven

Mazhar Ansari
5 min readJul 8, 2020

--

Note: While copy/paste the code snippet from blog please covert quotes and double quotes.

In this blog we will try to learn how we can promote Mule API’s along with the Mule application using Anypoint CLI, Jenkins and Maven.

Prerequisite?

  • Jenkins must be installed
  • Anypoint CLI should be installed on machine where Jenkins are installed
  • Maven is installed

Overview of Anypoint CLI:

JSON Extractor:

  • Windows don’t have command line utility to parse JSON file or JSON data so we tried to achieve same using Batch script
@if (@CodeSection == @Batch) @then@echo off & setlocalcscript /nologo /e:JScript “%~f0” %*
goto :EOF
@end // end batch / begin JScript hybrid chimeravar htmlfile = WSH.CreateObject(‘htmlfile’);
htmlfile.write(‘<meta http-equiv=”x-ua-compatible” content=”IE=9" />’);
var JSON = htmlfile.parentWindow.JSON;
//needs file existence checks
var jsloc=WScript.Arguments.Item(0);
var jsonPath=WScript.Arguments.Item(1);
FSOObj = new ActiveXObject(“Scripting.FileSystemObject”);
var txtFile=FSOObj.OpenTextFile(jsloc,1);
var json=txtFile.ReadAll();
try {
var jParsed=JSON.parse(json);
}catch(err) {
WScript.Echo(“Failed to parse the json content”);
htmlfile.close();
txtFile.close();
WScript.Exit(1);
}
WScript.Echo(eval(“JSON.stringify(jParsed.”+jsonPath+”)”));htmlfile.close();
txtFile.close();
  • This script we use to parse the JSON file
  • Save above script into a ‘.bat’ file and store into a directory
  • Sample exchange.json file
{
“main”: “demo.raml”,
“name”: “demo”,
“classifier”: “raml”,
“tags”: [],
“groupId”: “3a84e9e1–6a31–4847–9ea0–5a672256f55e”,
“assetId”: “demo”,
“version”: “1.0.0”,
“apiVersion”: “v1”,
“originalFormatVersion”: “1.0”
}

Note: For Unix JQ is an alternate option for above mention script to parse the JSON data

API Promotion using Batch Script and Anypoint CLI:

This script do below mentioned steps

  • We get version of API from exchange.json file stored in Mule Project
  • Get API Instance ID using Anypoint CLI command
  • Update API manager with new API Specification
@echo off
set user=%1
set pwd=%2
set sourceEnv=%3
set asset=%4
echo %user% %pwd% %sourceEnv% %asset%
echo app started
for /f %%i in (‘jsonextractor.bat exchange.json version’) do set Version=%%i
echo version is %Version%
for /f %%i in (‘jsonextractor.bat exchange.json apiversion’) do set apiVersion=%%i
echo version is %apiVersion%
CALL anypoint-cli — username=%user% — password=%pwd% designcenter project publish %asset% — apiVersion %apiVersion%
for /f %%i in (‘anypoint-cli — username=%user% — password=%pwd% — environment=%sourceEnv% api-mgr api list -f “Instance ID” — assetId %asset% -o text’) do set apiInstance=%%i
echo api instance is %apiInstance%
CALL anypoint-cli — username=%user% — password=%pwd% — environment=%sourceEnv% api-mgr api change-specification %apiInstance% %Version%
  • This script will use last step script (exchange.bat)
  • This script we will use to promote the API using Jenkins Pipeline
  • Save above script into a ‘.bat’ file and store into a directory

Jenkins Pipeline File:

Jenkins Pipeline (or simply “Pipeline”) is a suite of plugins which supports implementing and integrating continuous delivery pipelines into Jenkins.

A continuous delivery pipeline is an automated expression of your process for getting software from version control right through to your users and customers.

The sample pipeline has 4 stages.

  • Build Mule Application: We use maven command to build the jar
  • Test Mule Application: We use maven command to test application all the MUnits test cases which is part of the application will be executed and report will be generated
  • Promote Mule API to Env: This step execute batch file created at last step to promote the API
  • Deploy Mule Application to Env: This step again execute the maven commands to deploy the application to cloudhub or on prem server through anypoint platform
pipeline {
agent any
stages {
stage(‘Build Mule Application’) {
steps {
bat ‘mvn clean install’
}
}
stage(‘Test Mule Application’) {
steps {
echo ‘Test Mule Application…’
bat ‘mvn test’
}
}
stage(‘Promote Mule API to <ENV>’) {
environment {
ANYPOINT_CREDENTIALS = credentials(‘wp.anypoint.credentials’)
}
steps {
echo getChangedFilesList()
script {
if (getChangedFilesList() == ‘true’) {
echo “${ANYPOINT_CREDENTIALS_USR}”
echo “${ANYPOINT_CREDENTIALS_PSW}”
bat ‘api-promotion.bat %ANYPOINT_CREDENTIALS_USR% %ANYPOINT_CREDENTIALS_PSW% <ENV> <API-Name>’
}
}
}
}
stage(‘Deploy Mule Application CloudHub’) {
environment {
ANYPOINT_CREDENTIALS = credentials(‘wp.anypoint.credentials’)
}
steps {
echo ‘Deploying only because of code commit…’
echo “ worker is ${params.workerType}”
bat ‘mvn package deploy -DmuleDeploy -Dusername=${ANYPOINT_CREDENTIALS_USR} -Dpassword=${ANYPOINT_CREDENTIALS_PSW} -Denvironment=<ENV> -DworkerType=<WorkerType> -Dworkers=1 -Dregion=<REGION>’
}
}
}
}
String getChangedFilesList() {
print “entering function”
changedFiles = “”
for (changeLogSet in currentBuild.changeSets) {
for (entry in changeLogSet.getItems()) { // for each commit in the detected changes
for (file in entry.getAffectedFiles()) {
changedFiles += (file.getPath() + “ “) // add changed file to list
}
}
}
print “entering function”
if (changedFiles.contains(“exchange.json”)) {
return “true”
} else {
return “false”
}
}

Please choose <ENV> according to the target environment in cloudhub.

Please choose <API-Name> according to the API Name in exchange or design center.

Please choose <WorkType> and <Region> values based on below list according to your requirement.

Accepted values for region:

  • us-east-1 — US East (N. Virginia)
  • us-west-2 — US West (Oregon)
  • eu-west-1 — EU (Ireland)
  • ap-southeast-2 — Asia Pacific (Sydney)
  • ap-southeast-1 — Asia Pacific (Singapore)
  • us-west-1 — US West (N. California)
  • eu-central-1 — EU (Frankfurt)
  • ap-northeast-1 — Asia Pacific (Tokyo)
  • eu-west-2 — EU (London)
  • ca-central-1 — Canada (Central)
  • sa-east-1 — South America (São Paulo)
  • us-east-2 — US East (Ohio)

Accepted values for workerType:

  • MICRO(0.1 vCores)
  • SMALL (0.2 vCores),
  • MEDIUM (1 vCores)
  • LARGE (2 vCores)
  • XLARGE (4 vCores)
  • XXLARGE (8 vCores)
  • 4XLARGE (16 vCores)

Note: Save above script at JenkinsFile and store in project folder

Jenkins Project File:

  • Save the following file as demo.xml
<?xml version=’1.1' encoding=’UTF-8'?>
<flow-definition plugin=”workflow-job@2.39">
<actions>
<org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin=”pipeline-model-definition@1.7.0"/>
<org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction plugin=”pipeline-model-definition@1.7.0">
<jobProperties/>
<triggers/>
<parameters/>
<options/>
</org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction>
</actions>
<description></description>
<keepDependencies>false</keepDependencies>
<properties>
<org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
<triggers>
<hudson.triggers.SCMTrigger>
<spec>* * * * *</spec>
<ignorePostCommitHooks>false</ignorePostCommitHooks>
</hudson.triggers.SCMTrigger>
</triggers>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>
<definition class=”org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition” plugin=”workflow-cps@2.80">
<scm class=”hudson.plugins.git.GitSCM” plugin=”git@4.3.0">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>https://useraccount@bitbucket.org/useraccount/demo.git</url>
<credentialsId>443b704b-d1f1–4889-add4–5aa19384673e</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/master</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class=”list”/>
<extensions/>
</scm>
<scriptPath>jenkinsfile</scriptPath>
<lightweight>true</lightweight>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>
  • Change the user <url>https://useraccount@bitbucket.org/useraccount/demo.git</url> with your SCM URL
  • Run below command to export the Jenkins pipeline
  • java -jar jenkins-cli.jar -s http://<JenkinsServerIP>:<PORT>/ -auth <UserName>:<Password> -webSocket create-job <JOB-Name>< demo.xml
  • Note: Jenkins-cli.jar should be already downloaded. To download jar please use below URL
  • http://<JenkinsServerIP>:<PORT>/jnlpJars/jenkins-cli.jar
  • Login to Jenkins
Jenkins Login Page
  • Click on recently create JOB (Demo)
JOB List
  • Click on Configure
JOB Menu
  • Update the credential
JOB Configuration
  • Save

Note: Two credentials should be created before executing the flow end to end. One for Anypoint credentials and Other for SCM credentials.

--

--

Mazhar Ansari
Mazhar Ansari

Written by Mazhar Ansari

I am seasoned Integration Architect with around 18+ yrs of exp. I have extensively worked on TIBCO and Mulesoft. Mainly in EAI, ESB, SOA, API and BPM projects.

No responses yet