diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 8b8928d..0000000 --- a/.gitignore +++ /dev/null @@ -1,66 +0,0 @@ -.DS_Store -temp.* -# Jenkins gitignore -work - -# Java gitignore -*.class - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# maven gitignore -target -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties - - -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea - -## File-based project format: -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -dummy.json - -bin -.classpath -.settings -.project -*.iml -*.ipr -*.iws diff --git a/Declarative-Jenkinsfile b/Declarative-Jenkinsfile deleted file mode 100644 index da5c1bd..0000000 --- a/Declarative-Jenkinsfile +++ /dev/null @@ -1,148 +0,0 @@ -#!groovy -/* - This is an sample Jenkins file for the Weather App, which is a node.js application that has unit test, code coverage - and functional verification tests, deploy to staging and production environment and use IBM Cloud DevOps gate. - We use this as an example to use our plugin in the Jenkinsfile - Basically, you need to specify required 4 environment variables and then you will be able to use the 4 different methods - for the build/test/deploy stage and the gate - */ -pipeline { - agent any - environment { - // You need to specify 4 required environment variables first, they are going to be used for the following IBM Cloud DevOps steps - IBM_CLOUD_DEVOPS_CREDS = credentials('BM_CRED') - IBM_CLOUD_DEVOPS_ORG = 'dlatest' - IBM_CLOUD_DEVOPS_APP_NAME = 'Weather-V1' - IBM_CLOUD_DEVOPS_TOOLCHAIN_ID = '1320cec1-daaa-4b63-bf06-7001364865d2' - IBM_CLOUD_DEVOPS_WEBHOOK_URL = 'WEBHOOK_URL_PLACEHOLDER' - } - tools { - nodejs 'recent' - } - stages { - stage('Build') { - environment { - // get git commit from Jenkins - GIT_COMMIT = sh(returnStdout: true, script: 'git rev-parse HEAD').trim() - GIT_BRANCH = 'master' - GIT_REPO = 'GIT_REPO_URL_PLACEHOLDER' - } - steps { - checkout scm - sh 'npm --version' - sh 'npm install' - sh 'grunt dev-setup --no-color' - } - // post build section to use "publishBuildRecord" method to publish build record - post { - success { - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"SUCCESS" - } - failure { - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"FAIL" - } - } - } - stage('Unit Test and Code Coverage') { - steps { - sh 'grunt dev-test-cov --no-color -f' - } - // post build section to use "publishTestResult" method to publish test result - post { - always { - publishTestResult type:'unittest', fileLocation: './mochatest.json' - publishTestResult type:'code', fileLocation: './tests/coverage/reports/coverage-summary.json' - } - } - } - stage('Deploy to Staging') { - steps { - // Push the Weather App to Bluemix, staging space - sh ''' - echo "CF Login..." - cf api https://api.ng.bluemix.net - cf login -u $IBM_CLOUD_DEVOPS_CREDS_USR -p $IBM_CLOUD_DEVOPS_CREDS_PSW -o $IBM_CLOUD_DEVOPS_ORG -s staging - - echo "Deploying...." - export CF_APP_NAME="staging-$IBM_CLOUD_DEVOPS_APP_NAME" - cf delete $CF_APP_NAME -f - cf push $CF_APP_NAME -n $CF_APP_NAME -m 64M -i 1 - - # use "cf icd --create-connection" to enable traceability - cf icd --create-connection $IBM_CLOUD_DEVOPS_WEBHOOK_URL $CF_APP_NAME - - export APP_URL=http://$(cf app $CF_APP_NAME | grep urls: | awk '{print $2}') - ''' - } - // post build section to use "publishDeployRecord" method to publish deploy record and notify OTC of stage status - post { - success { - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Staging", status: "SUCCESS" - sendDeployableMessage status: "SUCCESS" - } - failure { - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Staging", status: "FAILURE" - } - } - } - stage('FVT') { - //set the APP_URL as the environment variable for the fvt - environment { - APP_URL = "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net" - } - steps { - sh 'grunt fvt-test --no-color -f' - } - // post build section to use "publishTestResult" method to publish test result - post { - always { - publishTestResult type:'fvt', fileLocation: './mochafvt.json', environment: 'STAGING' - } - } - } - stage('Gate') { - steps { - // use "evaluateGate" method to leverage IBM Cloud DevOps gate - evaluateGate policy: 'Weather App Policy', forceDecision: 'true' - } - } - stage('Deploy to Prod') { - steps { - // Push the Weather App to Bluemix, production space - sh ''' - echo "CF Login..." - cf api https://api.ng.bluemix.net - cf login -u $IBM_CLOUD_DEVOPS_CREDS_USR -p $IBM_CLOUD_DEVOPS_CREDS_PSW -o $IBM_CLOUD_DEVOPS_ORG -s production - - echo "Deploying...." - export CF_APP_NAME="prod-$IBM_CLOUD_DEVOPS_APP_NAME" - cf delete $CF_APP_NAME -f - cf push $CF_APP_NAME -n $CF_APP_NAME -m 64M -i 1 - - # use "cf icd --create-connection" to enable traceability - cf icd --create-connection $IBM_CLOUD_DEVOPS_WEBHOOK_URL $CF_APP_NAME - - export APP_URL=http://$(cf app $CF_APP_NAME | grep urls: | awk '{print $2}') - ''' - } - // post build section to use "publishDeployRecord" method to publish deploy record and notify OTC of stage status - post { - success { - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Prod", status: "SUCCESS" - sendDeployableMessage status: "SUCCESS" - } - failure { - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Prod", status: "FAILURE" - } - } - } - } -} diff --git a/Declarative-SQ-Jenkinsfile b/Declarative-SQ-Jenkinsfile deleted file mode 100644 index 596d10d..0000000 --- a/Declarative-SQ-Jenkinsfile +++ /dev/null @@ -1,54 +0,0 @@ -pipeline { - agent any - environment { - // You need to specify 4 required environment variables first, they are going to be used for the following IBM Cloud DevOps steps - IBM_CLOUD_DEVOPS_CREDS = credentials('BM_CRED') - IBM_CLOUD_DEVOPS_ORG = 'dlatest' - IBM_CLOUD_DEVOPS_APP_NAME = 'Weather-V1' - IBM_CLOUD_DEVOPS_TOOLCHAIN_ID = '1320cec1-daaa-4b63-bf06-7001364865d2' - IBM_CLOUD_DEVOPS_WEBHOOK_URL = 'WEBHOOK_URL_PLACEHOLDER' - } - stages { - stage('SCM') { - steps { - git 'https://github.com/ccox-IBM/simple-toolchain-1488583960040.git' - } - } - stage ('SonarQube analysis') { - steps { - script { - // requires SonarQube Scanner 2.8+ - def scannerHome = tool 'Default SQ Scanner'; - - withSonarQubeEnv('Default SQ Server') { - - env.SQ_HOSTNAME = SONAR_HOST_URL; - env.SQ_AUTHENTICATION_TOKEN = SONAR_AUTH_TOKEN; - env.SQ_PROJECT_KEY = "simple-toolchain-1488583960040"; - - sh "${scannerHome}/bin/sonar-scanner \ - -Dsonar.projectKey=${SQ_PROJECT_KEY} \ - -Dsonar.sources=. \ - -Dsonar.organization=ccox-ibm-github"; - } - } - } - } - stage ("SonarQube Quality Gate") { - steps { - script { - - def qualitygate = waitForQualityGate() - if (qualitygate.status != "OK") { - error "Pipeline aborted due to quality gate coverage failure: ${qualitygate.status}" - } - } - } - post { - always { - publishSQResults SQHostURL: "${SQ_HOSTNAME}", SQAuthToken: "${SQ_AUTHENTICATION_TOKEN}", SQProjectKey:"${SQ_PROJECT_KEY}" - } - } - } - } -} \ No newline at end of file diff --git a/Demo-Jenkinsfile b/Demo-Jenkinsfile deleted file mode 100644 index 41ba467..0000000 --- a/Demo-Jenkinsfile +++ /dev/null @@ -1,104 +0,0 @@ -#!groovy -/* - This is an sample Jenkins file for the Weather App, which is a node.js application that has unit test, code coverage - and functional verification tests, deploy to staging and production environment and use IBM Cloud DevOps gate. - We use this as an example to use our plugin in the Jenkinsfile - Basically, you need to specify required 4 environment variables and then you will be able to use the 4 different methods - for the build/test/deploy stage and the gate - */ -pipeline { - agent any - environment { - // You need to specify 4 required environment variables first, they are going to be used for the following IBM Cloud DevOps steps - IBM_CLOUD_DEVOPS_CREDS = credentials('BLUEMIX_CREDENTIAL_ID') - IBM_CLOUD_DEVOPS_ORG = 'ORG_NAME_PLACEHOLDER' - IBM_CLOUD_DEVOPS_APP_NAME = 'APP_NAME_PLACEHOLDER' - IBM_CLOUD_DEVOPS_TOOLCHAIN_ID = 'TOOLCHAIN_ID_PLACEHOLDER' - GIT_REPO = 'https://github.com/open-toolchain/DemoDRA' - } - tools { - nodejs 'recent' // your nodeJS installation name in Jenkins - } - stages { - stage('SCM') { - steps { - deleteDir() - git "${GIT_REPO}" - } - } - stage('Build') { - environment { - // get git commit from Jenkins - GIT_COMMIT = sh(returnStdout: true, script: 'git rev-parse HEAD').trim() - GIT_BRANCH = 'master' - } - steps {git - sh 'npm --version' - sh 'npm install' - sh 'grunt dev-setup --no-color' - } - // post build section to use "publishBuildRecord" method to publish build record - post { - success { - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"SUCCESS" - } - failure { - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"FAIL" - } - } - } - stage('Unit Test and Code Coverage') { - steps { - sh 'grunt dev-test-cov --no-color -f' - } - // post build section to use "publishTestResult" method to publish test result - post { - always { - publishTestResult type:'unittest', fileLocation: './mochatest.json' - publishTestResult type:'code', fileLocation: './tests/coverage/reports/coverage-summary.json' - } - } - } - stage('Deploy to Staging') { - steps { - // Push the Weather App to Bluemix, staging space - sh ''' - echo "Deploying App to Staging" - - ''' - } - // post build section to use "publishDeployRecord" method to publish deploy record and notify OTC of stage status - post { - success { - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - } - failure { - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - } - } - } - stage('Gate') { - steps { - // use "evaluateGate" method to leverage IBM Cloud DevOps gate - evaluateGate policy: 'POLICY_NAME_PLACEHOLDER', forceDecision: 'true' - } - } - stage('Deploy to Prod') { - steps { - // Push the Weather App to Bluemix, production space - sh ''' - echo "Deploying to Prod" - ''' - } - // post build section to use "publishDeployRecord" method to publish deploy record and notify OTC of stage status - post { - success { - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - } - failure { - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - } - } - } - } -} diff --git a/Jenkins-Pipeline-Support.md b/Jenkins-Pipeline-Support.md deleted file mode 100644 index 95c06c9..0000000 --- a/Jenkins-Pipeline-Support.md +++ /dev/null @@ -1,219 +0,0 @@ -To use IBM Cloud DevOps with the Jenkins pipeline project, you can follow the [declarative Jenkinsfile](https://github.ibm.com/oneibmcloud/Jenkins-IBM-Bluemix-Toolchains/blob/pipeline-support/Declarative-Jenkinsfile) or [scripted jenkinsfile](https://github.ibm.com/oneibmcloud/Jenkins-IBM-Bluemix-Toolchains/blob/pipeline-support/Scripted-Jenkinsfile) - -## Prerequisites -Make sure you are using Jenkins 2.X and have all pipeline related plugins installed and updated to the latest version -It has been test for Jenkins pipeline job with Pipeline plugin 2.5 version. - -## 1. Create a Pipeline Job - -Create a pipeline job, and configure it, there are 2 ways that you can do - -1. In the Pipeline section, choose Pipeline script from SCM, and set up the SCM that your pipeline wants to run on and specify the Path of the Jenkinsfile. You can use the [declarative Jenkinsfile](https://github.ibm.com/oneibmcloud/Jenkins-IBM-Bluemix-Toolchains/blob/pipeline-support/Declarative-Jenkinsfile) as an example -2. Set up the SCM in the general configuration, then in the Pipeline section, choose Pipeline script, and put your scripted Jenkinsfile script there. You can use the [scripted jenkinsfile](https://github.ibm.com/oneibmcloud/Jenkins-IBM-Bluemix-Toolchains/blob/pipeline-support/Scripted-Jenkinsfile) as an example - - -## 2. Expose the required environment variables to all steps -The plugin requires 5 environment variables defined as follow: - -1. `IBM_CLOUD_DEVOPS_CREDS` - the bluemix credentials ID that you defined in the jenkins, e.g `IBM_CLOUD_DEVOPS_CREDS = credentials('BM_CRED')`, by using the `credentials` command, it will set two environment variables automatically: - 1. `IBM_CLOUD_DEVOPS_CREDS_USR` for username - 2. `IBM_CLOUD_DEVOPS_CREDS_PSW` for password -2. `IBM_CLOUD_DEVOPS_ORG` - the bluemix org that you are going to use -3. `IBM_CLOUD_DEVOPS_APP_NAME` - the name of your application -4. `IBM_CLOUD_DEVOPS_TOOLCHAIN_ID` - the toolchain id that you are using, you can get the toolchain id from the url after the toolchain is created. e.g https://console.ng.bluemix.net/devops/toolchains/TOOLCHAIN_ID. -5. `IBM_CLOUD_DEVOPS_WEBHOOK_URL` - the webhook obtained from the Jenkins card on your toolchain. - -In the plugin, we are going to refer to these environment variables and credentials to interact with IBM Cloud DevOps -Here is an example to use it in the Jenkinsfile (a.k.a Declarative Pipeline) - -``` -environment { - IBM_CLOUD_DEVOPS_CREDS = credentials('BM_CRED') - IBM_CLOUD_DEVOPS_ORG = 'dlatest' - IBM_CLOUD_DEVOPS_APP_NAME = 'Weather-App' - IBM_CLOUD_DEVOPS_TOOLCHAIN_ID = '1320cec1-daaa-4b63-bf06-7001364865d2' - IBM_CLOUD_DEVOPS_WEBHOOK_URL = 'https://jenkins:5a55555a-a555-5555-5555-a555aa55a555:55555555-5555-5555-5555-555555555555@devops-api.ng.bluemix.net/v1/toolint/messaging/webhook/publish' - } -``` - -Notes: `credentials` is only available for Declarative Pipeline. For those using Scripted Pipeline, see the documentation for the `withCredentials` step. -For the Scripted Pipeline, use `withEnv` instead of `environment`. You can refer to [Scripted Jenkinsfile](https://github.ibm.com/oneibmcloud/Jenkins-IBM-Bluemix-Toolchains/blob/pipeline-support/Scripted-Jenkinsfile) as an example - - -## 3. Use the IBM Cloud DevOps steps -We provide 4 steps to upload the build/test/deploy information and use the IBM Cloud DevOps Gate - -### 1. publishBuildRecord -Publish the build record to the IBM Cloud DevOps, there are 4 required parameters: - -1. gitBranch - the name of the git branch -2. gitCommit - the commit id of the repo -3. gitRepo - the url of the git repo -4. result - the result of the build stage, the value should be either "SUCCESS" or "FAIL" - -Here is a usage example -``` -publishBuildRecord gitBranch: "${GIT_MASTER}", gitCommit: "${GIT_COMMIT}", gitRepo: "https://github.com/xunrongl/DemoDRA-1", result:"SUCCESS" -``` - -Note: Currently, jenkins pipeline does not expose git information to the environment variables, you can get git commit using `sh(returnStdout: true, script: 'git rev-parse HEAD').trim()` - -### 2. publishTestResult -Publish the test result to the IBM Cloud DevOps, there are 2 required parameters: - -1. type - the accepted values currently are only 3: - 1. `unittest` for unit test - 2. `fvt` for functional verification test - 3. `code` for code coverage -2. fileLocation - the result file location - -Here is a usage example -``` -publishTestResult type:'unittest', fileLocation: './mochatest.json' -publishTestResult type:'code', fileLocation: './tests/coverage/reports/coverage-summary.json' -``` - -### 3. publishSQResults - -Configure a SonarQube scanner and a SonarQube server by following the instructions in the [SonarQube docs](https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Jenkins). - -Publish the results of your latest SonarQube scan to IBM Cloud DevOps, there are 3 required parameters - -1. (required) SQHostURL - the host portion of your SonarQube scanner's URL. This is extracted from the configuration above. -2. (required) SQAuthToken - your SonarQube API authentication token. This is extracted from the configuration above. -3. (required) SQProjectKey - the project key of the SonarQube project you wish to scan. - -Here is a usage example -``` -stage ('SonarQube analysis') { - steps { - script { - def scannerHome = tool 'Default SQ Scanner'; - withSonarQubeEnv('Default SQ Server') { - - env.SQ_HOSTNAME = SONAR_HOST_URL; - env.SQ_AUTHENTICATION_TOKEN = SONAR_AUTH_TOKEN; - env.SQ_PROJECT_KEY = "My Project Key"; - - run SonarQube scan ... - } - } - } -} -stage ("SonarQube Quality Gate") { - steps { - ... - } - post { - always { - publishSQResults SQHostURL: "${SQ_HOSTNAME}", SQAuthToken: "${SQ_AUTHENTICATION_TOKEN}", SQProjectKey:"${SQ_PROJECT_KEY}" - } - } -} -``` - -### 4. publishDeployRecord -Publish the deploy record to the IBM Cloud DevOps, there are 2 required and 1 optional parameters: - -1. (required) environment - the environment that you deploy your app to, if you deploy your app to the staging environment, use "STAGING"; if it is production environment, use "PRODUCTION" -2. (required) result - the result of the build stage, the value should be either "SUCCESS" or "FAIL" -3. (optional) appUrl - the application url that you deploy your app to - -Here is a usage example -``` -publishDeployRecord environment: "STAGING", appUrl: "http://staging-Weather-App.mybluemix.net", result:"SUCCESS" -``` - -### 5. evaluateGate -Use IBM Cloud DevOps Gate in the pipeline, there is 1 required and 1 optional parameters: - -1. (required) policy - the policy name that you define in the DevOps Insight -2. (optional) forceDecision - if you want to abort the pipeline based on the gate decision, set it to be `true`. It is `false` by default if you don't pass the parameter - -Here is a usage example -``` -evaluateGate policy: 'Weather App Policy', forceDecision: 'true' -``` - -### 6. notifyOTC -Configure your Jenkins jobs to send notifications to your Bluemix Toolchain by following the instructions in the [Bluemix Docs](https://console.ng.bluemix.net/docs/services/ContinuousDelivery/toolchains_integrations.html#jenkins). (Please disregard steps 8.d, 8.e, and 8.f because these are tailored for freestyle jobs.) - -Publish the status of your pipeline stages to your Bluemix Toolchain: - -1. (required) stageName - the name of the current pipeline stage. -2. (required) status - the completion status of the current pipeline stage. ('SUCCESS', 'FAILURE', and 'ABORTED' will be augmented with color) -3. (optional) webhookUrl - the webhook obtained from the Jenkins card on your toolchain. - -#### Declarative Pipeline Example: -``` -stage('Deploy') { - steps { - ... - } - - post { - success { - notifyOTC stageName: "Deploy", status: "SUCCESS" - } - failure { - notifyOTC stageName: "Deploy", status: "FAILURE" - } - } -} -``` - -#### Scripted Pipeline Example: -``` -stage('Deploy') { - try { - ... (deploy steps) - - notifyOTC stageName: "Deploy", status: "SUCCESS" - } - catch (Exception e) { - notifyOTC stageName: "Deploy", status: "FAILURE" - } -} -``` - -#### Optional -In both cases you can override the IBM_CLOUD_DEVOPS_WEBHOOK_URL: -``` -notifyOTC stageName: "Deploy", status: "FAILURE", webhookUrl: "https://different-webhook-url@devops-api.ng.bluemix.net/v1/toolint/messaging/webhook/publish" -``` - -### 7. Traceability -Configure your Jenkins environment to create a deployable mapping message in order to send traceability information to your bluemix toolchain and track code deployments through tags, labels, and comments in your Git repository (repo) by following the instructions below. - -#### Add the space environment variable -Traceability requires an additional space environment variable defined as follow: - -`IBM_CLOUD_DEVOPS_SPACE` - the bluemix space where your application is deployed. - -#### Send deployable mapping message -Simply add the following line to you deploy stage: - sendDeployableMessage status: "SUCCESS" - -#### Optional -You can override the `IBM_CLOUD_DEVOPS_WEBHOOK_URL`: - -``` -sendDeployableMessage status: "SUCCESS", webhookUrl: "https://different-webhook-url@devops-api.ng.bluemix.net/v1/toolint/messaging/webhook/publish" - -#### Important -Add this line only when stage status is "SUCCESS". Any other status will be discarded. - -#### Scripted Pipeline Example: -``` -stage('Deploy') { - try { - ... (deploy steps) - - notifyOTC stageName: "Deploy", status: "SUCCESS" - sendDeployableMessage status: "SUCCESS" - } - catch (Exception e) { - notifyOTC stageName: "Deploy", status: "FAILURE" - } -} -``` diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0cc1d03..0000000 --- a/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2016, 2017 IBM Corporation - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Scripted-Jenkinsfile b/Scripted-Jenkinsfile deleted file mode 100644 index 6a547b1..0000000 --- a/Scripted-Jenkinsfile +++ /dev/null @@ -1,136 +0,0 @@ -#!groovy -node { - git url: 'https://github.com/xunrongl/DemoDRA-1.git' - tool name: 'recent', type: 'nodejs' - - withEnv([ - // You need to specify 3 required environment variables and your bluemix credentials first, they are going to be used for the following IBM Cloud DevOps steps - 'IBM_CLOUD_DEVOPS_ORG=dlatest', - 'IBM_CLOUD_DEVOPS_APP_NAME=Weather-V1-Scripted', - 'IBM_CLOUD_DEVOPS_TOOLCHAIN_ID=1320cec1-daaa-4b63-bf06-7001364865d2' - 'IBM_CLOUD_DEVOPS_WEBHOOK_URL=WEBHOOK_URL_PLACEHOLDER' - ]) { - //specify your bluemix credentials, please use "IBM_CLOUD_DEVOPS_CREDS_USR" for usernameVariable, "IBM_CLOUD_DEVOPS_CREDS_PSW" for passwordVariable - withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'BM_CRED', - usernameVariable: 'IBM_CLOUD_DEVOPS_CREDS_USR', passwordVariable: 'IBM_CLOUD_DEVOPS_CREDS_PSW']]) { - - // work around to get the git commit id - def gitCommit = sh(returnStdout: true, script: "git rev-parse HEAD").trim() - stage('Build') { - withEnv(["GIT_COMMIT=${gitCommit}", - 'GIT_BRANCH=master', - "GIT_REPO=GIT_REPO_URL_PLACEHOLDER"]) { - try { - sh 'npm install' - sh 'grunt dev-setup --no-color' - - // use "publishBuildRecord" method to publish build record - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"SUCCESS" - } - catch (Exception e) { - publishBuildRecord gitBranch: "${GIT_BRANCH}", gitCommit: "${GIT_COMMIT}", gitRepo: "${GIT_REPO}", result:"FAIL" - } - } - stage('Unit Test and Code Coverage') { - sh 'grunt dev-test-cov --no-color -f' - // use "publishTestResult" method to publish test result - publishTestResult type:'unittest', fileLocation: './mochatest.json' - publishTestResult type:'code', fileLocation: './tests/coverage/reports/coverage-summary.json' - } - stage('Deploy to Staging') { - try { - // Push the Weather App to Bluemix, staging space - sh ''' - echo "CF Login..." - cf api https://api.ng.bluemix.net - cf login -u $IBM_CLOUD_DEVOPS_CREDS_USR -p $IBM_CLOUD_DEVOPS_CREDS_PSW -o $IBM_CLOUD_DEVOPS_ORG -s staging - - echo "Deploying...." - export CF_APP_NAME="staging-$IBM_CLOUD_DEVOPS_APP_NAME" - cf delete $CF_APP_NAME -f - cf push $CF_APP_NAME -n $CF_APP_NAME -m 64M -i 1 - - # use "cf icd --create-connection" to enable traceability - cf icd --create-connection $IBM_CLOUD_DEVOPS_WEBHOOK_URL $CF_APP_NAME - - export APP_URL=http://$(cf app $CF_APP_NAME | grep urls: | awk '{print $2}') - ''' - // use "publishDeployRecord" method to publish deploy record - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Staging", status: "SUCCESS" - sendDeployableMessage status: "SUCCESS" - } - catch (Exception e) { - publishDeployRecord environment: "STAGING", appUrl: "http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Staging", status: "FAILURE" - } - } - stage('FVT') { - withEnv(["APP_URL=http://staging-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net"]) { - sh 'grunt fvt-test --no-color -f' - } - - // use "publishTestResult" method to publish test result - publishTestResult type:'fvt', fileLocation: './mochafvt.json', environment: 'STAGING' - } - stage('Gate') { - // use "evaluateGate" method to leverage IBM Cloud DevOps gate - evaluateGate policy: 'Weather App Policy', forceDecision: 'true' - } - stage('Deploy to Prod') { - try { - // Push the Weather App to Bluemix, production space - sh ''' - echo "CF Login..." - cf api https://api.ng.bluemix.net - cf login -u $IBM_CLOUD_DEVOPS_CREDS_USR -p $IBM_CLOUD_DEVOPS_CREDS_PSW -o $IBM_CLOUD_DEVOPS_ORG -s production - - echo "Deploying...." - export CF_APP_NAME="prod-$IBM_CLOUD_DEVOPS_APP_NAME" - cf delete $CF_APP_NAME -f - cf push $CF_APP_NAME -n $CF_APP_NAME -m 64M -i 1 - - # use "cf icd --create-connection" to enable traceability - cf icd --create-connection $IBM_CLOUD_DEVOPS_WEBHOOK_URL $CF_APP_NAME - - export APP_URL=http://$(cf app $CF_APP_NAME | grep urls: | awk '{print $2}') - ''' - - // use "publishDeployRecord" method to publish deploy record - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"SUCCESS" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Prod", status: "SUCCESS" - sendDeployableMessage status: "SUCCESS" - } - catch(Exception e) { - publishDeployRecord environment: "PRODUCTION", appUrl: "http://prod-${IBM_CLOUD_DEVOPS_APP_NAME}.mybluemix.net", result:"FAIL" - // use "notifyOTC" method to notify otc of stage status - notifyOTC stageName: "Deploy to Prod", status: "FAILURE" - } - } - } - } - } -} - - -/* - -void withDevOpsEnv(List envVars = [], def body) { - List jobEnv = [ - 'IBM_CLOUD_DEVOPS_ORG=lix@us.ibm.com', - 'IBM_CLOUD_DEVOPS_APP_NAME=Weather-V1-Xunrong-Scripted', - 'IBM_CLOUD_DEVOPS_TOOLCHAIN_ID=1320cec1-daaa-4b63-bf06-7001364865d2' - ] - - // Add any additional environment variables. - jobEnv.addAll(envVars) - - // Invoke the body closure we're passed within the environment we've created. - withEnv(jobEnv) { - body.call() - } -} - */ diff --git a/Scripted-SQ-Jenkinsfile b/Scripted-SQ-Jenkinsfile deleted file mode 100644 index 183a194..0000000 --- a/Scripted-SQ-Jenkinsfile +++ /dev/null @@ -1,48 +0,0 @@ -node { - - withEnv([ - // You need to specify 3 required environment variables and your bluemix credentials first, they are going to be used for the following IBM Cloud DevOps steps - 'IBM_CLOUD_DEVOPS_ORG=dlatest', - 'IBM_CLOUD_DEVOPS_APP_NAME=Weather-V1-Scripted', - 'IBM_CLOUD_DEVOPS_TOOLCHAIN_ID=1320cec1-daaa-4b63-bf06-7001364865d2', - 'IBM_CLOUD_DEVOPS_WEBHOOK_URL=WEBHOOK_URL_PLACEHOLDER' - ]) { - withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'BM_CRED', - usernameVariable: 'IBM_CLOUD_DEVOPS_CREDS_USR', passwordVariable: 'IBM_CLOUD_DEVOPS_CREDS_PSW']]) { - stage('SCM') { - git 'https://github.com/ccox-IBM/simple-toolchain-1488583960040.git'; - } - stage('SonarQube analysis') { - // requires SonarQube Scanner 2.8+ - def scannerHome = tool 'Default SQ Scanner'; - - withSonarQubeEnv('Default SQ Server') { - - env.SQ_HOSTNAME = SONAR_HOST_URL; - env.SQ_AUTHENTICATION_TOKEN = SONAR_AUTH_TOKEN; - env.SQ_PROJECT_KEY = "simple-toolchain-1488583960040"; - - sh "${scannerHome}/bin/sonar-scanner \ - -Dsonar.projectKey=${SQ_PROJECT_KEY} \ - -Dsonar.sources=. \ - -Dsonar.organization=ccox-ibm-github"; - //save host and auth token used to configure the SQ tool - } - } - - stage("Quality Gate") { - - timeout(time: 1, unit: 'HOURS') { // Just in case something goes wrong, pipeline will be killed after a timeout - - def qg = waitForQualityGate(); // Reuse taskId previously collected by withSonarQubeEnv - - publishSQResults SQHostURL: "${SQ_HOSTNAME}", SQAuthToken: "${SQ_AUTHENTICATION_TOKEN}", SQProjectKey: "${SQ_PROJECT_KEY}" - - if (qg.status != 'OK') { - error "Pipeline aborted due to quality gate failure: ${qg.status}" - } - } - } - } - } -} diff --git a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.jar b/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.jar deleted file mode 100644 index e87bcaf..0000000 Binary files a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.jar and /dev/null differ diff --git a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.pom b/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.pom deleted file mode 100644 index b9c94b6..0000000 --- a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/1.1.3/cloudfoundry-client-lib-shaded-custom-1.1.3.pom +++ /dev/null @@ -1,9 +0,0 @@ - - - 4.0.0 - org.cloudfoundry - cloudfoundry-client-lib-shaded-custom - 1.1.3 - POM was created from install:install-file - diff --git a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/maven-metadata-local.xml b/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/maven-metadata-local.xml deleted file mode 100644 index 8954669..0000000 --- a/lib/org/cloudfoundry/cloudfoundry-client-lib-shaded-custom/maven-metadata-local.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - org.cloudfoundry - cloudfoundry-client-lib-shaded-custom - - 1.1.3 - - 1.1.3 - - 20150821193926 - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 4ae7917..0000000 --- a/pom.xml +++ /dev/null @@ -1,188 +0,0 @@ - - - - 4.0.0 - com.ibm.devops - ibm-cloud-devops - 1.1.4-SNAPSHOT - hpi - IBM Cloud DevOps - This plugin can be used to integrate your Jenkins pipelines and jobs with IBM DevOps Insights offering. The IBM DevOps Insights offering tracks your deployment risk based on the data that you publish to it. It provides Gates so that you can stop builds from getting deployed if the Gate policy is not met. The offering also provides analysis of your Git repo. For example, it can provide trends for large commits, error prone files, and team dynamics. Very soon, the offering will provide more trends, e.g., Deploy Frequency, Build Frequency, Unit Tests and Code Coverage and Function Verification Tests for builds that have deployed to production or other environments. - https://wiki.jenkins-ci.org/display/JENKINS/IBM+Cloud+DevOps+Plugin - - - org.jenkins-ci.plugins - plugin - 2.12 - - - - - - org.jenkins-ci.tools - maven-hpi-plugin - - true - - - - - - src/main/resources - true - - - - - - 2.7.1 - 8 - 2.4.4 - 1.7.0RC2 - - - - - maven.jenkins-ci.org - https://repo.jenkins-ci.org/releases/ - - - maven.jenkins-ci.org - https://repo.jenkins-ci.org/snapshots/ - - - - - - MIT License - http://opensource.org/licenses/MIT - - - - - - xunrongl - Xunrong Li - xunrongli@us.ibm.com - - - patjoy - Patrick Joy - patrick.joy1@ibm.com - - - imvijay2007 - Vijay Jegaselvan - vjegase@us.ibm.com - - - ejodet - Eric Jodet - eric_jodet@fr.ibm.com - - - - - scm:git:git://git@github.com/jenkinsci/ibm-cloud-devops-plugin.git - scm:git:git@github.com:jenkinsci/ibm-cloud-devops-plugin.git - ibm-cloud-devops-1.1.1 - - - - - repo.jenkins-ci.org - https://repo.jenkins-ci.org/public/ - - - - Local repository - file://${basedir}/lib - - - spring-snapshots - Spring Snapshots - http://repo.spring.io/snapshot - - true - - - - - - - repo.jenkins-ci.org - http://repo.jenkins-ci.org/public/ - - - - - - org.jenkins-ci.plugins - credentials - 2.1.1 - - - org.apache.httpcomponents - httpcore - 4.4.5 - - - org.apache.httpcomponents - httpmime - 4.3.6 - - - org.apache.httpcomponents - httpclient - 4.3.6 - - - com.google.code.gson - gson - 2.6.2 - - - - - org.cloudfoundry - cloudfoundry-client-lib-shaded-custom - 1.1.3 - - - org.jenkins-ci.plugins.workflow - workflow-step-api - 1.14 - - - org.mockito - mockito-core - 2.7.22 - test - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - - - diff --git a/screenshots/DRA-Gate.png b/screenshots/DRA-Gate.png deleted file mode 100644 index f3ea177..0000000 Binary files a/screenshots/DRA-Gate.png and /dev/null differ diff --git a/screenshots/PostBuild-WebHookNotification.png b/screenshots/PostBuild-WebHookNotification.png deleted file mode 100644 index c3da63b..0000000 Binary files a/screenshots/PostBuild-WebHookNotification.png and /dev/null differ diff --git a/screenshots/Set-Parameterized-Webhook.png b/screenshots/Set-Parameterized-Webhook.png deleted file mode 100644 index 3a196c6..0000000 Binary files a/screenshots/Set-Parameterized-Webhook.png and /dev/null differ diff --git a/screenshots/Upload-Build-Info.png b/screenshots/Upload-Build-Info.png deleted file mode 100644 index 4142fb5..0000000 Binary files a/screenshots/Upload-Build-Info.png and /dev/null differ diff --git a/screenshots/Upload-Deployment-Info.png b/screenshots/Upload-Deployment-Info.png deleted file mode 100644 index d6f763f..0000000 Binary files a/screenshots/Upload-Deployment-Info.png and /dev/null differ diff --git a/screenshots/Upload-Test-Result.png b/screenshots/Upload-Test-Result.png deleted file mode 100644 index 5426485..0000000 Binary files a/screenshots/Upload-Test-Result.png and /dev/null differ diff --git a/screenshots/track-deployment-of-code-changes.png b/screenshots/track-deployment-of-code-changes.png deleted file mode 100644 index 809b067..0000000 Binary files a/screenshots/track-deployment-of-code-changes.png and /dev/null differ diff --git a/src/main/java/com/ibm/devops/dra/AbstractDevOpsAction.java b/src/main/java/com/ibm/devops/dra/AbstractDevOpsAction.java deleted file mode 100644 index 33be41b..0000000 --- a/src/main/java/com/ibm/devops/dra/AbstractDevOpsAction.java +++ /dev/null @@ -1,935 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.common.collect.ImmutableMap; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import hudson.EnvVars; -import hudson.ProxyConfiguration; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.Recorder; -import hudson.util.ListBoxModel; -import hudson.util.Secret; -import jenkins.model.Jenkins; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.cloudfoundry.client.lib.CloudCredentials; -import org.cloudfoundry.client.lib.CloudFoundryClient; -import org.cloudfoundry.client.lib.CloudFoundryException; -import org.cloudfoundry.client.lib.HttpProxyConfiguration; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Pattern; -import java.util.Scanner; -import java.util.logging.Logger; -import java.util.logging.Level; - -/** - * Abstract DRA Builder to share common method between two different post-build actions - */ -public abstract class AbstractDevOpsAction extends Recorder { - - public final static Logger LOGGER = Logger.getLogger(AbstractDevOpsAction.class.getName()); - - private final static String ORG= "&&organization_guid:"; - private final static String SPACE= "&&space_guid:"; - - private static Map TARGET_API_MAP = ImmutableMap.of( - "production", "https://api.ng.bluemix.net", - "dev", "https://api.stage1.ng.bluemix.net", - "new", "https://api.stage1.ng.bluemix.net", - "stage1", "https://api.stage1.ng.bluemix.net" - ); - - private static Map ORGANIZATIONS_URL_MAP = ImmutableMap.of( - "production", "https://api.ng.bluemix.net/v2/organizations?q=name:", - "dev", "https://api.stage1.ng.bluemix.net/v2/organizations?q=name:", - "new", "https://api.stage1.ng.bluemix.net/v2/organizations?q=name:", - "stage1", "https://api.stage1.ng.bluemix.net/v2/organizations?q=name:" - ); - - private static Map SPACES_URL_MAP = ImmutableMap.of( - "production", "https://api.ng.bluemix.net/v2/spaces?q=name:", - "dev", "https://api.stage1.ng.bluemix.net/v2/spaces?q=name:", - "new", "https://api.stage1.ng.bluemix.net/v2/spaces?q=name:", - "stage1", "https://api.stage1.ng.bluemix.net/v2/spaces?q=name:" - ); - - private static Map APPS_URL_MAP = ImmutableMap.of( - "production", "https://api.ng.bluemix.net/v2/apps?q=name:", - "dev", "https://api.stage1.ng.bluemix.net/v2/apps?q=name:", - "new", "https://api.stage1.ng.bluemix.net/v2/apps?q=name:", - "stage1", "https://api.stage1.ng.bluemix.net/v2/apps?q=name:" - ); - - private static Map TOOLCHAINS_URL_MAP = ImmutableMap.of( - "production", "https://otc-api.ng.bluemix.net/api/v1/toolchains?organization_guid=", - "dev", "https://otc-api.stage1.ng.bluemix.net/api/v1/toolchains?organization_guid=", - "stage1", "https://otc-api-integration.stage1.ng.bluemix.net/api/v1/toolchains?organization_guid=", - "new", "https://otc-api.stage1.ng.bluemix.net/api/v1/toolchains?organization_guid=" - ); - - private static Map POLICIES_URL_MAP = ImmutableMap.of( - "production", "https://dra.ng.bluemix.net/api/v4/organizations/{org_name}/toolchainids/{toolchain_name}/policies", - "dev", "https://dev-dra.stage1.ng.bluemix.net/api/v4/organizations/{org_name}/toolchainids/{toolchain_name}/policies", - "new", "https://new-dra.stage1.ng.bluemix.net/api/v4/organizations/{org_name}/toolchainids/{toolchain_name}/policies", - "stage1", "https://dra.stage1.ng.bluemix.net/api/v4/organizations/{org_name}/toolchainids/{toolchain_name}/policies" - ); - - private static Map DLMS_ENV_MAP = ImmutableMap.of( - "production", "https://dlms.ng.bluemix.net/v2", - "dev", "https://dev-dlms.stage1.ng.bluemix.net/v2", - "new", "https://new-dlms.stage1.ng.bluemix.net/v2", - "stage1", "https://dlms.stage1.ng.bluemix.net/v2" - ); - - private static Map GATE_DECISION_ENV_MAP = ImmutableMap.of( - "production", "https://dra.ng.bluemix.net/api/v4", - "dev", "https://dev-dra.stage1.ng.bluemix.net/api/v4", - "new", "https://new-dra.stage1.ng.bluemix.net/api/v4", - "stage1", "https://dra.stage1.ng.bluemix.net/api/v4" - ); - - private static Map CONTROL_CENTER_ENV_MAP = ImmutableMap.of( - "production", "https://console.ng.bluemix.net/devops/insights/#!/", - "dev", "https://dev-console.stage1.ng.bluemix.net/devops/insights/#!/", - "new", "https://new-console.stage1.ng.bluemix.net/devops/insights/#!/", - "stage1", "https://console.stage1.ng.bluemix.net/devops/insights/#!/" - ); - - private static Map DRA_REPORT_ENV_MAP = ImmutableMap.of( - "production", "https://dra.ng.bluemix.net/report/", - "dev", "https://dev-dra.stage1.ng.bluemix.net/report/", - "new", "https://new-dra.stage1.ng.bluemix.net/report/", - "stage1", "https://dra.stage1.ng.bluemix.net/report/" - ); - - public static void printPluginVersion(ClassLoader loader, PrintStream printStream) { - final Properties properties = new Properties(); - try { - properties.load(loader.getResourceAsStream("plugin.properties")); - printStream.println("[IBM Cloud DevOps] version: " + properties.getProperty("version")); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static String chooseTargetAPI(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String target_api = TARGET_API_MAP.get(environment); - if (!Util.isNullOrEmpty(target_api)) { - return target_api; - } - } - - return TARGET_API_MAP.get("production"); - } - - public static String chooseToolchainsUrl(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String toolchains_url = TOOLCHAINS_URL_MAP.get(environment); - if (!Util.isNullOrEmpty(toolchains_url)) { - return toolchains_url; - } - } - - return TOOLCHAINS_URL_MAP.get("production"); - } - - public static String chooseOrganizationsUrl(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String organizations_url = ORGANIZATIONS_URL_MAP.get(environment); - if (!Util.isNullOrEmpty(organizations_url)) { - return organizations_url; - } - } - - return ORGANIZATIONS_URL_MAP.get("production"); - } - - public static String chooseSpacesUrl(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String spaces_url = SPACES_URL_MAP.get(environment); - if (!Util.isNullOrEmpty(spaces_url)) { - return spaces_url; - } - } - - return SPACES_URL_MAP.get("production"); - } - - public static String chooseAppsUrl(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String apps_url = APPS_URL_MAP.get(environment); - if (!Util.isNullOrEmpty(apps_url)) { - return apps_url; - } - } - - return APPS_URL_MAP.get("production"); - } - - public static String choosePoliciesUrl(String environment) { - if (!Util.isNullOrEmpty(environment)) { - String policies_url = POLICIES_URL_MAP.get(environment); - if (!Util.isNullOrEmpty(policies_url)) { - return policies_url; - } - } - - return POLICIES_URL_MAP.get("production"); - } - - - /** - * choose DLMS Url for different environment (production, stage1, new, dev) - * @param envStr - * @return - */ - - public static String chooseDLMSUrl(String envStr) { - if (!Util.isNullOrEmpty(envStr)) { - String dlmsUrl = DLMS_ENV_MAP.get(envStr); - if (!Util.isNullOrEmpty(dlmsUrl)) { - return dlmsUrl; - } - } - - return DLMS_ENV_MAP.get("production"); - } - - /** - * choose DRA Url for different environment (production, stage1, new, dev) - * @param envStr - * @return - */ - public static String chooseDRAUrl(String envStr) { - if (!Util.isNullOrEmpty(envStr)) { - String draUrl = GATE_DECISION_ENV_MAP.get(envStr); - if (!Util.isNullOrEmpty(draUrl)) { - return draUrl; - } - } - - return GATE_DECISION_ENV_MAP.get("production"); - } - - /** - * choose control center Url for different environment (production, stage1, new, dev) - * @param envStr - * @return - */ - public static String chooseControlCenterUrl(String envStr) { - if (!Util.isNullOrEmpty(envStr)) { - String ccUrl = CONTROL_CENTER_ENV_MAP.get(envStr); - if (!Util.isNullOrEmpty(ccUrl)) { - return ccUrl; - } - } - return CONTROL_CENTER_ENV_MAP.get("production"); - } - - /** - * choose report prefix url for different environment (production, stage1, new, dev) - * @param envStr - * @return - */ - public static String chooseReportUrl(String envStr) { - if (!Util.isNullOrEmpty(envStr)) { - String ccUrl = CONTROL_CENTER_ENV_MAP.get(envStr); - if (!Util.isNullOrEmpty(ccUrl)) { - return ccUrl; - } - } - return CONTROL_CENTER_ENV_MAP.get("production"); - } - - /** - * check if the root url in the jenkins is set correctly - * @param printStream - * @return - */ - public static boolean checkRootUrl(PrintStream printStream) { - if (Util.isNullOrEmpty(Jenkins.getInstance().getRootUrl())) { - printStream.println( - "[IBM Cloud DevOps] The Jenkins global root url is not set. Please set it to use this postbuild Action. \"Manage Jenkins > Configure System > Jenkins URL\""); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Build Info."); - return false; - } - return true; - } - - /** - * Get the Bluemix Token using Cloud Foundry as the authentication with DLMS and DRA backend - * @param context - the current job - * @param credentialsId - the credential id in Jenkins - * @param targetAPI - the target api that used for logging in to the Bluemix - * @return the bearer token - */ - public static String getBluemixToken(Job context, String credentialsId, String targetAPI) throws Exception { - - try { - List standardCredentials = CredentialsProvider.lookupCredentials( - StandardUsernamePasswordCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(targetAPI).build()); - - StandardUsernamePasswordCredentials credentials = - CredentialsMatchers.firstOrNull(standardCredentials, CredentialsMatchers.withId(credentialsId)); - - if (credentials == null || credentials.getUsername() == null || credentials.getPassword() == null) { - throw new Exception("Failed to get Credentials"); - } - CloudCredentials cloudCredentials = new CloudCredentials(credentials.getUsername(), Secret.toString(credentials.getPassword())); - if (cloudCredentials == null) { - throw new Exception("Failed to get Cloud Credentials"); - } - - URL url = new URL(targetAPI); - HttpProxyConfiguration configuration = buildProxyConfiguration(url); - - CloudFoundryClient client = new CloudFoundryClient(cloudCredentials, url, configuration, true); - return "bearer " + client.login().toString(); - - } catch (MalformedURLException e) { - throw e; - } catch (CloudFoundryException e) { - throw e; - } - } - - public static String getBluemixToken(ItemGroup context, String credentialsId, String targetAPI) throws Exception { - - try { - List standardCredentials = CredentialsProvider.lookupCredentials( - StandardUsernamePasswordCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(targetAPI).build()); - - StandardUsernamePasswordCredentials credentials = - CredentialsMatchers.firstOrNull(standardCredentials, CredentialsMatchers.withId(credentialsId)); - - if (credentials == null || credentials.getUsername() == null || credentials.getPassword() == null) { - throw new Exception("Failed to get Credentials"); - } - CloudCredentials cloudCredentials = new CloudCredentials(credentials.getUsername(), Secret.toString(credentials.getPassword())); - if (cloudCredentials == null) { - throw new Exception("Failed to get Cloud Credentials"); - } - - URL url = new URL(targetAPI); - HttpProxyConfiguration configuration = buildProxyConfiguration(url); - - CloudFoundryClient client = new CloudFoundryClient(cloudCredentials, url, configuration, true); - return "bearer " + client.login().toString(); - - } catch (MalformedURLException e) { - throw e; - } catch (CloudFoundryException e) { - throw e; - } - } - - public static String getBluemixToken(String username, String password, String targetAPI) throws MalformedURLException, CloudFoundryException { - try { - - CloudCredentials cloudCredentials = new CloudCredentials(username, password); - - URL url = new URL(targetAPI); - HttpProxyConfiguration configuration = buildProxyConfiguration(url); - - CloudFoundryClient client = new CloudFoundryClient(cloudCredentials, url, configuration, true); - return "bearer " + client.login().toString(); - - } catch (MalformedURLException e) { - throw e; - } catch (CloudFoundryException e) { - throw e; - } - } - - /** - * build proxy for cloud foundry http connection - * @param targetURL - target API URL - * @return the full target URL - */ - private static HttpProxyConfiguration buildProxyConfiguration(URL targetURL) { - ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; - if (proxyConfig == null) { - return null; - } - - String host = targetURL.getHost(); - for (Pattern p : proxyConfig.getNoProxyHostPatterns()) { - if (p.matcher(host).matches()) { - return null; - } - } - - return new HttpProxyConfiguration(proxyConfig.name, proxyConfig.port); - } - - /** - * get the root project - * @param job - the source job - * @return the root project - */ - private static Job getRootProject(Job job) { - if (job instanceof AbstractProject) { - return ((AbstractProject)job).getRootProject(); - } else { - return job; - } - } - - // retrieve the "folder" (jenkins root if no folder used) for this build - private static ItemGroup getItemGroup(Run build) { - return getRootProject(build.getParent()).getParent(); - } - - - /** - * Recursive function to locate the triggered build - * @param job - the target job - * @param parent - the current job - * @return the specific build of the target job - */ - private static Run getBuild(Job job, Run parent) { - Run result = null; - - // Upstream job for matrix will be parent project, not only individual configuration: - List jobNames = new ArrayList<>(); - jobNames.add(job.getFullName()); - if ((job instanceof AbstractProject) && ((AbstractProject)job).getRootProject() != job) { - jobNames.add(((AbstractProject)job).getRootProject().getFullName()); - } - - List> upstreamBuilds = new ArrayList<>(); - - for (Cause cause: parent.getCauses()) { - if (cause instanceof Cause.UpstreamCause) { - Cause.UpstreamCause upstream = (Cause.UpstreamCause) cause; - Run upstreamRun = upstream.getUpstreamRun(); - if (upstreamRun != null) { - upstreamBuilds.add(upstreamRun); - } - } - } - - if (parent instanceof AbstractBuild) { - AbstractBuild parentBuild = (AbstractBuild)parent; - - Map parentUpstreamBuilds = parentBuild.getUpstreamBuilds(); - for (Map.Entry buildEntry : parentUpstreamBuilds.entrySet()) { - upstreamBuilds.add(buildEntry.getKey().getBuildByNumber(buildEntry.getValue())); - } - } - - for (Run upstreamBuild : upstreamBuilds) { - Run run; - - if(upstreamBuild == null) { - continue; - } - if (jobNames.contains(upstreamBuild.getParent().getFullName())) { - // Use the 'job' parameter instead of directly the 'upstreamBuild', because of Matrix jobs. - run = job.getBuildByNumber(upstreamBuild.getNumber()); - } else { - // Figure out the parent job and do a recursive call to getBuild - run = getBuild(job, upstreamBuild); - } - - if (run != null){ - if ((result == null) || (result.getNumber() > run.getNumber())) { - result = run; - } - } - - } - - return result; - } - - /** - * locate triggered build - * @param build - the current running build of this job - * @param name - the build job name that you are going to locate - * @param printStream - logger - * @return - */ - public static Run getTriggeredBuild(Run build, String name, EnvVars envVars, PrintStream printStream) { - // if user specify the build job as current job or leave it empty - if (name == null || name.isEmpty() || name.equals(build.getParent().getName())) { - printStream.println("[IBM Cloud DevOps] Current job is the build job"); - return build; - } else { - name = envVars.expand(name); - Job job = Jenkins.getInstance().getItem(name, getItemGroup(build), Job.class); - if (job != null) { - Run src = getBuild(job, build); - if (src == null) { - // if user runs the test job independently - printStream.println("[IBM Cloud DevOps] Are you running the test job independently? Use the last successful build of the build job"); - src = job.getLastSuccessfulBuild(); - } - - return src; - } else { - // if user does not specify the build job or can not find the build job that user specifies - printStream.println("[IBM Cloud DevOps] ERROR: Failed to find the build job, please check the build job name"); - return null; - } - } - } - - /** - * Get the build number - * @param build - * @return - */ - public String getBuildNumber(String jobName, Run build) { - - String jName = ""; - Scanner s = new Scanner(jobName).useDelimiter("/"); - while(s.hasNext()){ // this will loop through the string until the last string(job name) is reached. - jName = s.next(); - } - s.close(); - - String buildNumber = jName + ":" + build.getNumber(); - return buildNumber; - } - - /** - * Get a list of toolchains using given token and organization name. - * @param token - * @param orgName - * @return - */ - public static ListBoxModel getToolchainList(String token, String orgName, String environment, Boolean debug_mode) { - - LOGGER.setLevel(Level.INFO); - - if(debug_mode){ - LOGGER.info("#######################"); - LOGGER.info("TOKEN:" + token); - LOGGER.info("ORG:" + orgName); - LOGGER.info("ENVIRONMENT:" + environment); - } - - String orgId = getOrgId(token, orgName, environment, debug_mode); - ListBoxModel emptybox = new ListBoxModel(); - emptybox.add("","empty"); - - if(orgId == null) { - return emptybox; - } - - CloseableHttpClient httpClient = HttpClients.createDefault(); - String toolchains_url = chooseToolchainsUrl(environment); - if(debug_mode){ - LOGGER.info("GET TOOLCHAIN LIST URL:" + toolchains_url + orgId); - } - - HttpGet httpGet = new HttpGet(toolchains_url + orgId); - - httpGet = addProxyInformation(httpGet); - - httpGet.setHeader("Authorization", token); - CloseableHttpResponse response = null; - - try { - response = httpClient.execute(httpGet); - String resStr = EntityUtils.toString(response.getEntity()); - - if(debug_mode){ - LOGGER.info("RESPONSE FROM TOOLCHAINS API:" + response.getStatusLine().toString()); - } - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject obj = element.getAsJsonObject(); - JsonArray items = obj.getAsJsonArray("items"); - ListBoxModel toolchainList = new ListBoxModel(); - - for (int i = 0; i < items.size(); i++) { - JsonObject toolchainObj = items.get(i).getAsJsonObject(); - String toolchainName = String.valueOf(toolchainObj.get("name")).replaceAll("\"", ""); - String toolchainID = String.valueOf(toolchainObj.get("toolchain_guid")).replaceAll("\"", ""); - toolchainList.add(toolchainName,toolchainID); - } - if(debug_mode){ - LOGGER.info("TOOLCHAIN LIST:" + toolchainList); - LOGGER.info("#######################"); - } - if(toolchainList.isEmpty()) { - if(debug_mode){ - LOGGER.info("RETURNED NO TOOLCHAINS."); - } - return emptybox; - } - return toolchainList; - } else { - LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); - return emptybox; - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return emptybox; - } - - public static String getOrgId(String token, String orgName, String environment, Boolean debug_mode) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - String organizations_url = chooseOrganizationsUrl(environment); - if(debug_mode){ - LOGGER.info("GET ORG_GUID URL:" + organizations_url + orgName); - } - - try { - HttpGet httpGet = new HttpGet(organizations_url + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20")); - - httpGet = addProxyInformation(httpGet); - - httpGet.setHeader("Authorization", token); - CloseableHttpResponse response = null; - - response = httpClient.execute(httpGet); - String resStr = EntityUtils.toString(response.getEntity()); - - if(debug_mode){ - LOGGER.info("RESPONSE FROM ORGANIZATIONS API:" + response.getStatusLine().toString()); - } - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject obj = element.getAsJsonObject(); - JsonArray resources = obj.getAsJsonArray("resources"); - - if(resources.size() > 0) { - JsonObject resource = resources.get(0).getAsJsonObject(); - JsonObject metadata = resource.getAsJsonObject("metadata"); - if(debug_mode){ - LOGGER.info("ORG_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); - } - return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); - } - else { - if(debug_mode){ - LOGGER.info("RETURNED NO ORGANIZATIONS."); - } - return null; - } - - } else { - if(debug_mode){ - LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); - } - return null; - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - public static String getSpaceId(String token, String spaceName, String environment, Boolean debug_mode) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - String spaces_url = chooseSpacesUrl(environment); - if(debug_mode){ - LOGGER.info("GET SPACE_GUID URL:" + spaces_url + spaceName); - } - - try { - HttpGet httpGet = new HttpGet(spaces_url + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20")); - - httpGet = addProxyInformation(httpGet); - - httpGet.setHeader("Authorization", token); - CloseableHttpResponse response = null; - - response = httpClient.execute(httpGet); - String resStr = EntityUtils.toString(response.getEntity()); - - if(debug_mode){ - LOGGER.info("RESPONSE FROM SPACES API:" + response.getStatusLine().toString()); - } - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject obj = element.getAsJsonObject(); - JsonArray resources = obj.getAsJsonArray("resources"); - - if(resources.size() > 0) { - JsonObject resource = resources.get(0).getAsJsonObject(); - JsonObject metadata = resource.getAsJsonObject("metadata"); - if(debug_mode){ - LOGGER.info("SPACE_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); - } - return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); - } - else { - if(debug_mode){ - LOGGER.info("RETURNED NO SPACES."); - } - return null; - } - - } else { - if(debug_mode){ - LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); - } - return null; - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - public static String getAppId(String token, String appName, String orgName, String spaceName, String environment, Boolean debug_mode) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - String apps_url = chooseAppsUrl(environment); - if(debug_mode){ - LOGGER.info("GET APPS_GUID URL:" + apps_url + appName + ORG + orgName + SPACE + spaceName); - } - - try { - HttpGet httpGet = new HttpGet(apps_url + URLEncoder.encode(appName, "UTF-8").replaceAll("\\+", "%20") + ORG + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20") + SPACE + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20")); - - httpGet = addProxyInformation(httpGet); - - httpGet.setHeader("Authorization", token); - CloseableHttpResponse response = null; - - response = httpClient.execute(httpGet); - String resStr = EntityUtils.toString(response.getEntity()); - - if(debug_mode){ - LOGGER.info("RESPONSE FROM APPS API:" + response.getStatusLine().toString()); - } - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject obj = element.getAsJsonObject(); - JsonArray resources = obj.getAsJsonArray("resources"); - - if(resources.size() > 0) { - JsonObject resource = resources.get(0).getAsJsonObject(); - JsonObject metadata = resource.getAsJsonObject("metadata"); - if(debug_mode){ - LOGGER.info("APP_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); - } - return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); - } - else { - if(debug_mode){ - LOGGER.info("RETURNED NO APPS."); - } - return null; - } - - } else { - if(debug_mode){ - LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); - } - return null; - } - - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } - - /** - * Get a list of policies that belong to an org - * @param token - * @param orgName - * @return - */ - - public static ListBoxModel getPolicyList(String token, String orgName, String toolchainName, String environment, Boolean debug_mode) { - - // get all jenkins job - ListBoxModel emptybox = new ListBoxModel(); - emptybox.add("","empty"); - - String url = choosePoliciesUrl(environment); - - - try { - url = url.replace("{org_name}", URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{toolchain_name}", URLEncoder.encode(toolchainName, "UTF-8").replaceAll("\\+", "%20")); - if(debug_mode){ - LOGGER.info("GET POLICIES URL:" + url); - } - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(url); - - httpGet = addProxyInformation(httpGet); - - httpGet.setHeader("Authorization", token); - CloseableHttpResponse response = null; - response = httpClient.execute(httpGet); - String resStr = EntityUtils.toString(response.getEntity()); - - if(debug_mode){ - LOGGER.info("RESPONSE FROM GET POLICIES URL:" + response.getStatusLine().toString()); - } - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonArray jsonArray = element.getAsJsonArray(); - - ListBoxModel model = new ListBoxModel(); - - for (int i = 0; i < jsonArray.size(); i++) { - JsonObject obj = jsonArray.get(i).getAsJsonObject(); - String name = String.valueOf(obj.get("name")).replaceAll("\"", ""); - model.add(name, name); - } - if(debug_mode){ - LOGGER.info("POLICY LIST:" + model); - LOGGER.info("#######################"); - } - return model; - } else { - if(debug_mode){ - LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); - } - return emptybox; - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return emptybox; - } - - /** - * write to the environment variables to pass to next build step - * @param build - the current build - * @param bluemixToken - the Bluemix Token - * @param buildId - the build number of the build job in the Jenkins - */ - public static void passEnvToNextBuildStep (Run build, final String bluemixToken, final String buildId) { - - build.addAction(new EnvironmentContributingAction() { - @Override - public String getIconFileName() { - return null; - } - - @Override - public String getDisplayName() { - return null; - } - - @Override - public String getUrlName() { - return null; - } - - public void buildEnvVars(AbstractBuild build, EnvVars envVars) { - if (envVars != null) { - if (!Util.isNullOrEmpty(bluemixToken)) { - envVars.put("DI_BM_TOKEN", bluemixToken); - } - - if (!Util.isNullOrEmpty(buildId)) { - envVars.put("DI_BUILD_ID", buildId); - } - } - } - } - ); - } - - public static HttpGet addProxyInformation (HttpGet instance) { - /* Add proxy to request if proxy settings in Jenkins UI are set. */ - ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; - if(proxyConfig != null){ - if((!Util.isNullOrEmpty(proxyConfig.name)) && proxyConfig.port != 0) { - HttpHost proxy = new HttpHost(proxyConfig.name, proxyConfig.port, "http"); - RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - instance.setConfig(config); - } - } - return instance; - } - - public static HttpPost addProxyInformation (HttpPost instance) { - /* Add proxy to request if proxy settings in Jenkins UI are set. */ - ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; - if(proxyConfig != null){ - if((!Util.isNullOrEmpty(proxyConfig.name)) && proxyConfig.port != 0) { - HttpHost proxy = new HttpHost(proxyConfig.name, proxyConfig.port, "http"); - RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - instance.setConfig(config); - } - } - return instance; - } - -} diff --git a/src/main/java/com/ibm/devops/dra/AbstractGateAction.java b/src/main/java/com/ibm/devops/dra/AbstractGateAction.java deleted file mode 100644 index 702aeab..0000000 --- a/src/main/java/com/ibm/devops/dra/AbstractGateAction.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import hudson.model.AbstractBuild; -import hudson.model.Action; - -/** - * Abstract Decision Text Action - */ -public abstract class AbstractGateAction implements Action { - public abstract Boolean getShowHeader(); - - public abstract String getText(); - - public abstract AbstractBuild getBuild(); - - @Override - public String getIconFileName() { - return null; - } - - @Override - public String getDisplayName() { - return null; - } - - @Override - public String getUrlName() { - return null; - } - -} diff --git a/src/main/java/com/ibm/devops/dra/BuildInfoModel.java b/src/main/java/com/ibm/devops/dra/BuildInfoModel.java deleted file mode 100644 index 58fc40f..0000000 --- a/src/main/java/com/ibm/devops/dra/BuildInfoModel.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -public class BuildInfoModel { - private String build_id; - private String job_url; - private String status; - private String timestamp; - private Repo repository; - - public BuildInfoModel(String build_id, String job_url, String status, String timestamp, Repo repository) { - this.build_id = build_id; - this.job_url = job_url; - this.status = status; - this.timestamp = timestamp; - this.repository = repository; - } - - public String getBuild_id() { - return build_id; - } - - public String getJob_url() { - return job_url; - } - - public String getStatus() { - return status; - } - - public String getTimestamp() { - return timestamp; - } - - public Repo getRepository() { - return repository; - } - - public static class Repo { - private String repository_url; - private String branch; - private String commit_id; - - public Repo(String repository_url, String branch, String commit_id) { - this.repository_url = repository_url; - this.branch = branch; - this.commit_id = commit_id; - } - - public String getRepository_url() { - return repository_url; - } - - public String getBranch() { - return branch; - } - - public String getCommit_id() { - return commit_id; - } - } - - -} diff --git a/src/main/java/com/ibm/devops/dra/BuildPublisherAction.java b/src/main/java/com/ibm/devops/dra/BuildPublisherAction.java deleted file mode 100644 index 6f20075..0000000 --- a/src/main/java/com/ibm/devops/dra/BuildPublisherAction.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import hudson.model.Action; - -public class BuildPublisherAction implements Action { - - private final String link; - - public BuildPublisherAction(String link) { - this.link = link; - } - - public String getLink() { - return link; - } - - @Override - public String getIconFileName() { - return null; - } - - @Override - public String getDisplayName() { - return null; - } - - @Override - public String getUrlName() { - return null; - } -} diff --git a/src/main/java/com/ibm/devops/dra/DeploymentInfoModel.java b/src/main/java/com/ibm/devops/dra/DeploymentInfoModel.java deleted file mode 100644 index e4aacc2..0000000 --- a/src/main/java/com/ibm/devops/dra/DeploymentInfoModel.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -public class DeploymentInfoModel { - private String app_url; - private String environment_name; - private String job_url; - private String status; - private String timestamp; - - public DeploymentInfoModel(String app_url, String environment_name, String job_url, String status, String timestamp) { - this.app_url = app_url; - this.environment_name = environment_name; - this.job_url = job_url; - this.status = status; - this.timestamp = timestamp; - } - - public String getApp_url() { - return app_url; - } - - public String getEnvironment_name() { - return environment_name; - } - - public String getJob_url() { - return job_url; - } - - public String getStatus() { - return status; - } - - public String getTimestamp() { - return timestamp; - } -} diff --git a/src/main/java/com/ibm/devops/dra/EnvironmentScope.java b/src/main/java/com/ibm/devops/dra/EnvironmentScope.java deleted file mode 100644 index e92d190..0000000 --- a/src/main/java/com/ibm/devops/dra/EnvironmentScope.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import hudson.Extension; -import hudson.model.AbstractDescribableImpl; -import hudson.model.Descriptor; -import org.kohsuke.stapler.DataBoundConstructor; - -public class EnvironmentScope extends AbstractDescribableImpl { - private boolean isBuild; - private boolean isAll; - private boolean isDeploy; - private String branchName; - private String envName; - - @DataBoundConstructor - public EnvironmentScope(String value, String branchName, String envName) { - switch (value) { - case "build": - this.isBuild = true; - this.isDeploy = false; - this.isAll = false; - break; - case "deploy": - this.isDeploy = true; - this.isBuild = false; - this.isAll = false; - break; - default: - this.isAll = true; - this.isBuild = false; - this.isDeploy = false; - break; - } - - this.branchName = branchName; - this.envName = envName; - } - - public boolean isBuild() { - return isBuild; - } - - public boolean isAll() { - return isAll; - } - - public boolean isDeploy() { - return isDeploy; - } - - public String getBranchName() { - return branchName; - } - - public void setBranchName(String branchName) { - this.branchName = branchName; - } - - public String getEnvName() { - return envName; - } - - public void setEnvName(String envName) { - this.envName = envName; - } - - - @Extension - public static class DescriptorImpl extends Descriptor { - @Override - public String getDisplayName() { - return "DevOps Insight Test Environment Scope"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/EvaluateGate.java b/src/main/java/com/ibm/devops/dra/EvaluateGate.java deleted file mode 100644 index 60fdddb..0000000 --- a/src/main/java/com/ibm/devops/dra/EvaluateGate.java +++ /dev/null @@ -1,615 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardListBoxModel; -import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import hudson.*; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Publisher; -import hudson.util.FormValidation; -import hudson.util.ListBoxModel; -import jenkins.model.Jenkins; -import jenkins.tasks.SimpleBuildStep; -import net.sf.json.JSONObject; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.kohsuke.stapler.AncestorInPath; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.QueryParameter; -import org.kohsuke.stapler.StaplerRequest; - -import javax.annotation.Nonnull; -import javax.servlet.ServletException; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URLEncoder; -import java.util.List; - - -/** - * Customized build step to get a gate decision from DRA backend - */ - -public class EvaluateGate extends AbstractDevOpsAction implements SimpleBuildStep{ - - private final static String CONTENT_TYPE = "application/json"; - - // form fields from UI - private final String policyName; - private String orgName; - private String buildJobName; - private String applicationName; - private String toolchainName; - private String environmentName; - private String credentialsId; - private boolean willDisrupt; - - private EnvironmentScope scope; - private String envName; - private boolean isDeploy; - - private String draUrl; - private PrintStream printStream; - private static String bluemixToken; - private static String preCredentials; - - //fields to support jenkins pipeline - private String username; - private String password; - // optional customized build number - private String buildNumber; - - // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" - @DataBoundConstructor - public EvaluateGate(String policyName, - String orgName, - String applicationName, - String toolchainName, - String environmentName, - String buildJobName, - String credentialsId, - boolean willDisrupt, - EnvironmentScope scope, - OptionalBuildInfo additionalBuildInfo) { - this.policyName = policyName; - this.orgName = orgName; - this.applicationName = applicationName; - this.toolchainName = toolchainName; - this.environmentName = environmentName; - this.buildJobName = buildJobName; - this.credentialsId = credentialsId; - this.willDisrupt = willDisrupt; - this.scope = scope; - this.envName = scope.getEnvName(); - this.isDeploy = scope.isDeploy(); - if (additionalBuildInfo == null) { - this.buildNumber = null; - } else { - this.buildNumber = additionalBuildInfo.buildNumber; - } - } - - public EvaluateGate(String policyName, - String orgName, - String applicationName, - String toolchainName, - String environmentName, - String username, - String password, - boolean willDisrupt) { - this.policyName = policyName; - this.orgName = orgName; - this.applicationName = applicationName; - this.toolchainName = toolchainName; - this.envName = environmentName; - this.willDisrupt = willDisrupt; - this.username = username; - this.password = password; - this.willDisrupt = willDisrupt; - } - - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - /** - * We'll use this from the config.jelly. - */ - - public String getPolicyName() { - return policyName; - } - - public String getOrgName() { - return orgName; - } - - public String getBuildJobName() { - return buildJobName; - } - - public String getApplicationName() { - return applicationName; - } - - public String getToolchainName() { - return toolchainName; - } - - public String getEnvironmentName() { - return environmentName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public boolean isWillDisrupt() { - return willDisrupt; - } - - public EnvironmentScope getScope() { - return scope; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getEnvName() { - return envName; - } - - public boolean isDeploy() { - return isDeploy; - } - - public static class OptionalBuildInfo { - private String buildNumber; - - @DataBoundConstructor - public OptionalBuildInfo(String buildNumber, String buildUrl) { - this.buildNumber = buildNumber; - } - } - - /** - * Override this method to get your operation done in the build step. When invoked, it is up to you, as a plugin developer - * to add your actions, and/or perform the operations required by your plugin in this build step. Equally, it is up - * to the developer to make the code run on the slave(master or an actual remote). This must be done given the builds - * workspace, as in build.getWorkspace(). The workspace is the link to the slave, as it is the representation of the - * remote file system. - * - * Build steps as you add them to your job configuration are executed sequentially, and the return value for your - * builder should indicate whether to execute the next build step in the list. - * @param build - the current build - * @param launcher - the launcher - * @param listener - the build listener - * @throws InterruptedException - * @throws IOException - */ - @Override - public void perform(@Nonnull Run build, @Nonnull FilePath filePath, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { - // This is where you 'build' the project. - printStream = listener.getLogger(); - printPluginVersion(this.getClass().getClassLoader(), printStream); - - // Get the project name and build id from environment - EnvVars envVars = build.getEnvironment(listener); - this.orgName = envVars.expand(this.orgName); - this.applicationName = envVars.expand(this.applicationName); - this.toolchainName = envVars.expand(this.toolchainName); - - if (!checkRootUrl(printStream)) { - return; - } - - if (this.isDeploy || !Util.isNullOrEmpty(this.envName)) { - this.environmentName = envVars.expand(this.envName); - } - - // verify if user chooses advanced option to input customized DRA - String env = getDescriptor().getEnvironment(); - this.draUrl = chooseDRAUrl(env); - String targetAPI = chooseTargetAPI(env); - - String buildNumber; - if (Util.isNullOrEmpty(this.buildNumber)) { - // locate the build job that triggers current build - Run triggeredBuild = getTriggeredBuild(build, buildJobName, envVars, printStream); - if (triggeredBuild == null) { - //failed to find the build job - return; - } else { - if (Util.isNullOrEmpty(this.buildJobName)) { - // handle the case which the build job name left empty, and the pipeline case - this.buildJobName = envVars.get("JOB_NAME"); - } - buildNumber = getBuildNumber(buildJobName, triggeredBuild); - } - } else { - buildNumber = envVars.expand(this.buildNumber); - } - - String bluemixToken; - // get the Bluemix token - try { - if (Util.isNullOrEmpty(this.credentialsId)) { - bluemixToken = getBluemixToken(username, password, targetAPI); - } else { - bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); - } - - printStream.println("[IBM Cloud DevOps] Log in successfully, get the Bluemix token"); - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); - printStream.println("[IBM Cloud DevOps]" + e.toString()); - return; - } - - // get decision response from DRA - try { - JsonObject decisionJson = getDecisionFromDRA(bluemixToken, buildNumber); - if (decisionJson == null) { - printStream.println("[IBM Cloud DevOps] get empty decision"); - return; - } - - // retrieve the decision id to compose the report link - String decisionId = String.valueOf(decisionJson.get("decision_id")); - // remove the double quotes - decisionId = decisionId.replace("\"",""); - - // Show Proceed or Failed based on the decision - String decision = String.valueOf(decisionJson.get("contents").getAsJsonObject().get("proceed")); - if (decision.equals("true")) { - decision = "Succeed"; - } else { - decision = "Failed"; - } - - String cclink = chooseControlCenterUrl(env) + "deploymentrisk?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" + this.toolchainName; - String reportUrl = chooseReportUrl(env) + "decisionreport?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" - + URLEncoder.encode(toolchainName, "UTF-8") + "&reportId=" + decisionId; - - GatePublisherAction action = new GatePublisherAction(reportUrl, cclink, decision, this.policyName, build); - build.addAction(action); - - printStream.println("************************************"); - printStream.println("Check IBM Cloud DevOps Gate Evaluation report here -" + reportUrl); - // console output for a "fail" decision - if (decision.equals("Failed")) { - printStream.println("IBM Cloud DevOps decision to proceed is: false"); - printStream.println("************************************"); - if (willDisrupt) { - Result result = Result.FAILURE; - build.setResult(result); - throw new AbortException("Decision is fail"); - } - return; - } - - // console output for a "proceed" decision - printStream.println("IBM Cloud DevOps decision to proceed is: true"); - printStream.println("************************************"); - return; - - } catch (IOException e) { - if (e instanceof AbortException) { - throw new AbortException("Decision is fail"); - } else { - printStream.print("[IBM Cloud DevOps] Error: " + e.getMessage()); - } - } - } - - @Override - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - /** - * Send a request to DRA backend to get a decision - * @param buildId - build ID, get from Jenkins environment - * @return - the response decision Json file - */ - private JsonObject getDecisionFromDRA(String bluemixToken, String buildId) throws IOException { - // create http client and post method - CloseableHttpClient httpClient = HttpClients.createDefault(); - String url = this.draUrl; - url = url + "/organizations/" + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20") + - "/toolchainids/" + URLEncoder.encode(toolchainName, "UTF-8").replaceAll("\\+", "%20") + - "/buildartifacts/" + URLEncoder.encode(applicationName, "UTF-8").replaceAll("\\+", "%20") + - "/builds/" + URLEncoder.encode(buildId, "UTF-8").replaceAll("\\+", "%20") + - "/policies/" + URLEncoder.encode(policyName, "UTF-8").replaceAll("\\+", "%20") + - "/decisions"; - if (!Util.isNullOrEmpty(this.environmentName)) { - url = url.concat("?environment_name=" + environmentName); - } - - HttpPost postMethod = new HttpPost(url); - - postMethod = addProxyInformation(postMethod); - postMethod.setHeader("Authorization", bluemixToken); - postMethod.setHeader("Content-Type", CONTENT_TYPE); - - CloseableHttpResponse response = httpClient.execute(postMethod); - String resStr = EntityUtils.toString(response.getEntity()); - - try { - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - printStream.println("[IBM Cloud DevOps] Get decision successfully"); - return resJson; - } else { - // if gets error status - printStream.println("[IBM Cloud DevOps] Error: Failed to get a decision, response status " + response.getStatusLine()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("message")) { - printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("message")); - } - } - } catch (JsonSyntaxException e) { - printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr); - } - - return null; - } - - - @Override - public EvaluateGate.EvaluateGateImpl getDescriptor() { - return (EvaluateGate.EvaluateGateImpl)super.getDescriptor(); - } - - /** - * Descriptor for {@link EvaluateGate}. Used as a singleton. - * The class is marked as public so that it can be accessed from views. - * - *

- * See src/main/resources/hudson/plugins/hello_world/HelloWorldBuilder/*.jelly - * for the actual HTML fragment for the configuration screen. - */ - @Extension // This indicates to Jenkins that this is an implementation of an extension point. - public static final class EvaluateGateImpl extends BuildStepDescriptor { - - private String environment; - private boolean debug_mode; - - /** - * In order to load the persisted global configuration, you have to - * call load() in the constructor. - */ - public EvaluateGateImpl() { - load(); - } - - /** - * Performs on-the-fly validation of the form field 'name'. - * - * @param value - * This parameter receives the value that the user has typed. - * @return - * Indicates the outcome of the validation. This is sent to the browser. - *

- * Note that returning {@link FormValidation#error(String)} does not - * prevent the form from being saved. It just means that a message - * will be displayed to the user. - */ - public FormValidation doCheckOrgName(@QueryParameter String value) - throws IOException, ServletException { - - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckApplicationName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckEnvironmentName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckToolchainName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Could not retrieve list of toolchains. Please check your username and password. If you have not created a toolchain, create one here."); - } - return FormValidation.ok(); - } - - public FormValidation doCheckPolicyName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Fail to get the policies, please check your username/password or org name and make sure you have created policies for this org and toolchain."); - } - return FormValidation.ok(); - } - - public FormValidation doTestConnection(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - preCredentials = credentialsId; - try { - String bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - if (Util.isNullOrEmpty(bluemixToken)) { - EvaluateGate.bluemixToken = bluemixToken; - return FormValidation.warning("Got empty token"); - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } catch (Exception e) { - return FormValidation.error("Failed to log in to Bluemix, please check your username/password"); - } - } else { - - return FormValidation.okWithMarkup("Connection successful"); - } - } - - /** - * This method is called to populate the credentials list on the Jenkins config page. - */ - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, - @QueryParameter("target") final String target) { - StandardListBoxModel result = new StandardListBoxModel(); - result.includeEmptyValue(); - result.withMatching(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), - CredentialsProvider.lookupCredentials( - StandardUsernameCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(target).build() - ) - ); - return result; - } - - /** - * Autocompletion for build job name field - * @param value - * @return - */ - public AutoCompletionCandidates doAutoCompleteBuildJobName(@QueryParameter String value) { - AutoCompletionCandidates auto = new AutoCompletionCandidates(); - - // get all jenkins job - List jobs = Jenkins.getInstance().getAllItems(Job.class); - for (int i = 0; i < jobs.size(); i++) { - String jobName = jobs.get(i).getName(); - - if (jobName.toLowerCase().startsWith(value.toLowerCase())) { - auto.add(jobName); - } - } - - return auto; - } - - /** - * This method is called to populate the policy list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillPolicyNameItems(@AncestorInPath ItemGroup context, - @QueryParameter final String orgName, - @QueryParameter final String toolchainName, - @QueryParameter final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - try { - // if user changes to a different credential, need to get a new token - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - preCredentials = credentialsId; - } - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######GATE : calling getPolicyList#######"); - } - return getPolicyList(bluemixToken, orgName, toolchainName, environment, debug_mode); - - } - - /** - * This method is called to populate the toolchain list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillToolchainNameItems(@AncestorInPath ItemGroup context, - @QueryParameter final String orgName, - @QueryParameter final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - try { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######GATE : calling getToolchainList#######"); - } - return getToolchainList(bluemixToken, orgName, environment, debug_mode); - } - - - /** - * Required Method - * This is used to determine if this build step is applicable for your chosen project type. (FreeStyle, MultiConfiguration, Maven) - * Some plugin build steps might be made to be only available to MultiConfiguration projects. - * - * @param aClass The current project - * @return a boolean indicating whether this build step can be chose given the project type - */ - public boolean isApplicable(Class aClass) { - // Indicates that this builder can be used with all kinds of project types - // return FreeStyleProject.class.isAssignableFrom(aClass); - return true; - } - - /** - * Required Method - * @return The text to be displayed when selecting your build in the project - */ - public String getDisplayName() { - return "IBM Cloud DevOps Gate"; - } - - @Override - public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { - // To persist global configuration information, - // set that to properties and call save(). - environment = formData.getString("environment"); - debug_mode = Boolean.parseBoolean(formData.getString("debug_mode")); - save(); - return super.configure(req,formData); - } - - public String getEnvironment() { - return environment; - } - public boolean getDebugMode() { - return debug_mode; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/GatePublisherAction.java b/src/main/java/com/ibm/devops/dra/GatePublisherAction.java deleted file mode 100644 index d4293e7..0000000 --- a/src/main/java/com/ibm/devops/dra/GatePublisherAction.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import hudson.model.Action; -import hudson.model.Run; - -/** - * DRA action for builds, show the decision and report link in the build status page - */ -public class GatePublisherAction implements Action { - - private final String text; - private final String riskDashboardLink; - private final String decision; - private final String policyName; - private final Run build; - - public GatePublisherAction(String text, String riskDashboardLink, String decision, String policyName, Run build) { - this.text = text; - this.riskDashboardLink = riskDashboardLink; - this.decision = decision; - this.policyName = policyName; - this.build = build; - } - - public String getText() { - return text; - } - - public String getRiskDashboardLink() { - return riskDashboardLink; - } - - public String getDecision() { - return decision; - } - - public String getPolicyName() { - return policyName; - } - - public Run getBuild() { - return build; - } - - @Override - public String getIconFileName() { - return null; - } - - @Override - public String getDisplayName() { - return null; - } - - @Override - public String getUrlName() { - return null; - } -} diff --git a/src/main/java/com/ibm/devops/dra/PublishBuild.java b/src/main/java/com/ibm/devops/dra/PublishBuild.java deleted file mode 100644 index 5642b8d..0000000 --- a/src/main/java/com/ibm/devops/dra/PublishBuild.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardListBoxModel; -import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.gson.*; -import hudson.*; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Publisher; -import hudson.util.FormValidation; -import hudson.util.ListBoxModel; -import jenkins.model.Jenkins; -import jenkins.tasks.SimpleBuildStep; -import net.sf.json.JSONObject; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.kohsuke.stapler.*; - -import javax.annotation.Nonnull; -import javax.servlet.ServletException; -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.TimeZone; -import java.net.URLEncoder; - -public class PublishBuild extends AbstractDevOpsAction implements SimpleBuildStep { - - private static String BUILD_API_URL = "/organizations/{org_name}/toolchainids/{toolchain_id}/buildartifacts/{build_artifact}/builds"; - private final static String CONTENT_TYPE_JSON = "application/json"; - private final static String CONTENT_TYPE_XML = "application/xml"; - - // form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainName; - - private String dlmsUrl; - private PrintStream printStream; - private File root; - private static String bluemixToken; - private static String preCredentials; - - // fields to support jenkins pipeline - private String result; - private String gitRepo; - private String gitBranch; - private String gitCommit; - private String username; - private String password; - // optional customized build number - private String buildNumber; - - - @DataBoundConstructor - public PublishBuild(String applicationName, String orgName, String credentialsId, String toolchainName, OptionalBuildInfo additionalBuildInfo) { - this.credentialsId = credentialsId; - this.applicationName = applicationName; - this.orgName = orgName; - this.toolchainName = toolchainName; - if (additionalBuildInfo == null) { - this.buildNumber = null; - } else { - this.buildNumber = additionalBuildInfo.buildNumber; - } - } - - public PublishBuild(String result, String gitRepo, String gitBranch, String gitCommit, String orgName, String applicationName, String toolchainName, String username, String password) { - this.gitRepo = gitRepo; - this.gitBranch = gitBranch; - this.gitCommit = gitCommit; - this.result = result; - this.applicationName = applicationName; - this.orgName = orgName; - this.toolchainName = toolchainName; - this.username = username; - this.password = password; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainName(String toolchainName) { - this.toolchainName = toolchainName; - } - - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - /** - * We'll use this from the config.jelly. - */ - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getToolchainName() { - return toolchainName; - } - - public String getBuildNumber() { - return buildNumber; - } - - public static class OptionalBuildInfo { - private String buildNumber; - - @DataBoundConstructor - public OptionalBuildInfo(String buildNumber, String buildUrl) { - this.buildNumber = buildNumber; - } - } - - @Override - public void perform(@Nonnull Run build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { - - printStream = listener.getLogger(); - printPluginVersion(this.getClass().getClassLoader(), printStream); - - // create root dir for storing test result - root = new File(build.getRootDir(), "DRA_TestResults"); - - // Get the project name and build id from environment - EnvVars envVars = build.getEnvironment(listener); - - if (!checkRootUrl(printStream)) { - return; - } - - // verify if user chooses advanced option to input customized DLMS - String env = getDescriptor().getEnvironment(); - this.dlmsUrl = chooseDLMSUrl(env) + BUILD_API_URL; - String targetAPI = chooseTargetAPI(env); - - //expand the variables - this.orgName = envVars.expand(this.orgName); - this.applicationName = envVars.expand(this.applicationName); - this.toolchainName = envVars.expand(this.toolchainName); - - // Check required parameters - if (Util.isNullOrEmpty(orgName) || Util.isNullOrEmpty(applicationName) || Util.isNullOrEmpty(toolchainName)) { - printStream.println("[IBM Cloud DevOps] Missing few required configurations"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Build Info."); - return; - } - - String bluemixToken; - // get the Bluemix token - try { - if (Util.isNullOrEmpty(this.credentialsId)) { - bluemixToken = getBluemixToken(username, password, targetAPI); - } else { - bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); - } - - printStream.println("[IBM Cloud DevOps] Log in successfully, get the Bluemix token"); - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); - printStream.println("[IBM Cloud DevOps]" + e.toString()); - return; - } - - String link = chooseControlCenterUrl(env) + "deploymentrisk?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" + this.toolchainName; - if (uploadBuildInfo(bluemixToken, build, envVars)) { - printStream.println("[IBM Cloud DevOps] Go to Control Center (" + link + ") to check your build status"); - BuildPublisherAction action = new BuildPublisherAction(link); - build.addAction(action); - } - } - - /** - * Construct the Git data model - * @param envVars - * @return - */ - public BuildInfoModel.Repo buildGitRepo(EnvVars envVars) { - String repoUrl = envVars.get("GIT_URL"); - String branch = envVars.get("GIT_BRANCH"); - String commitId = envVars.get("GIT_COMMIT"); - - repoUrl = Util.isNullOrEmpty(repoUrl) ? this.gitRepo : repoUrl; - branch = Util.isNullOrEmpty(branch) ? this.gitBranch : branch; - commitId = Util.isNullOrEmpty(commitId) ? this.gitCommit : commitId; - if (!Util.isNullOrEmpty(branch)) { - String[] parts = branch.split("/"); - branch = parts[parts.length - 1]; - } - - BuildInfoModel.Repo repo = new BuildInfoModel.Repo(repoUrl, branch, commitId); - return repo; - } - - /** - * Upload the build information to DLMS - API V2. - * @param bluemixToken - * @param build - * @param envVars - * @throws IOException - */ - private boolean uploadBuildInfo(String bluemixToken, Run build, EnvVars envVars) { - String resStr = ""; - - try { - CloseableHttpClient httpClient = HttpClients.createDefault(); - String url = this.dlmsUrl; - url = url.replace("{org_name}", URLEncoder.encode(this.orgName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{toolchain_id}", URLEncoder.encode(this.toolchainName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{build_artifact}", URLEncoder.encode(this.applicationName, "UTF-8").replaceAll("\\+", "%20")); - - String buildNumber; - if (Util.isNullOrEmpty(this.buildNumber)) { - buildNumber = getBuildNumber(envVars.get("JOB_NAME"), build); - } else { - buildNumber = envVars.expand(this.buildNumber); - } - - String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl(); - - HttpPost postMethod = new HttpPost(url); - postMethod = addProxyInformation(postMethod); - postMethod.setHeader("Authorization", bluemixToken); - postMethod.setHeader("Content-Type", CONTENT_TYPE_JSON); - - String buildStatus; - Result result = build.getResult(); - if ((result != null && result.equals(Result.SUCCESS)) - || (this.result != null && this.result.equals("SUCCESS"))) { - buildStatus = "pass"; - } else { - buildStatus = "fail"; - } - - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - dateFormat.setTimeZone(utc); - String timestamp = dateFormat.format(System.currentTimeMillis()); - - // build up the json body - Gson gson = new Gson(); - BuildInfoModel.Repo repo = buildGitRepo(envVars); - BuildInfoModel buildInfo = new BuildInfoModel(buildNumber, buildUrl, buildStatus, timestamp, repo); - - String json = gson.toJson(buildInfo); - StringEntity data = new StringEntity(json); - postMethod.setEntity(data); - CloseableHttpResponse response = httpClient.execute(postMethod); - resStr = EntityUtils.toString(response.getEntity()); - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - printStream.println("[IBM Cloud DevOps] Upload Build Information successfully"); - return true; - - } else { - // if gets error status - printStream.println("[IBM Cloud DevOps] Error: Failed to upload, response status " + response.getStatusLine()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("user_error")) { - printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("user_error")); - } - } - } catch (JsonSyntaxException e) { - printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr); - } catch (IllegalStateException e) { - // will be triggered when 403 Forbidden - try { - printStream.println("[IBM Cloud DevOps] Please check if you have the access to " + URLEncoder.encode(this.orgName, "UTF-8") + " org"); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - @Override - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - - // Overridden for better type safety. - // If your plugin doesn't really define any property on Descriptor, - // you don't have to do this. - @Override - public PublishBuild.PublishBuildActionImpl getDescriptor() { - return (PublishBuild.PublishBuildActionImpl)super.getDescriptor(); - } - - /** - * Descriptor for {@link PublishBuild}. Used as a singleton. - * The class is marked as public so that it can be accessed from views. - * - *

- * See src/main/resources/com/ibm/devops/dra/PublishBuild/*.jelly - * for the actual HTML fragment for the configuration screen. - */ - @Extension // This indicates to Jenkins that this is an implementation of an extension point. - public static final class PublishBuildActionImpl extends BuildStepDescriptor { - /** - * To persist global configuration information, - * simply store it in a field and call save(). - * - *

- * If you don't want fields to be persisted, use transient. - */ - - /** - * In order to load the persisted global configuration, you have to - * call load() in the constructor. - */ - public PublishBuildActionImpl() { - super(PublishBuild.class); - load(); - } - - /** - * Performs on-the-fly validation of the form field 'credentialId'. - * - * @param value - * This parameter receives the value that the user has typed. - * @return - * Indicates the outcome of the validation. This is sent to the browser. - *

- * Note that returning {@link FormValidation#error(String)} does not - * prevent the form from being saved. It just means that a message - * will be displayed to the user. - */ - - private String environment; - private boolean debug_mode; - - public FormValidation doCheckOrgName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckToolchainName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Could not retrieve list of toolchains. Please check your username and password. If you have not created a toolchain, create one here."); - } - return FormValidation.ok(); - } - - public FormValidation doCheckApplicationName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckEnvironmentName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doTestConnection(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - preCredentials = credentialsId; - try { - String newToken = getBluemixToken(context, credentialsId, targetAPI); - if (Util.isNullOrEmpty(newToken)) { - bluemixToken = newToken; - return FormValidation.warning("Got empty token"); - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } catch (Exception e) { - return FormValidation.error("Failed to log in to Bluemix, please check your username/password"); - } - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } - - /** - * This method is called to populate the credentials list on the Jenkins config page. - */ - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, - @QueryParameter("target") final String target) { - StandardListBoxModel result = new StandardListBoxModel(); - result.includeEmptyValue(); - result.withMatching(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), - CredentialsProvider.lookupCredentials( - StandardUsernameCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(target).build() - ) - ); - return result; - } - - /** - * This method is called to populate the toolchain list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillToolchainNameItems(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId, - @QueryParameter("orgName") final String orgName) { - String targetAPI = chooseTargetAPI(environment); - try { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######UPLOAD BUILD INFO : calling getToolchainList#######"); - } - ListBoxModel toolChainListBox = getToolchainList(bluemixToken, orgName, environment, debug_mode); - return toolChainListBox; - - } - - /** - * Required Method - * This is used to determine if this build step is applicable for your chosen project type. (FreeStyle, MultiConfiguration, Maven) - * Some plugin build steps might be made to be only available to MultiConfiguration projects. - * - * @param aClass The current project - * @return a boolean indicating whether this build step can be chose given the project type - */ - public boolean isApplicable(Class aClass) { - // Indicates that this builder can be used with all kinds of project types - // return FreeStyleProject.class.isAssignableFrom(aClass); - return true; - } - - /** - * Required Method - * @return The text to be displayed when selecting your build in the project - */ - public String getDisplayName() { - return "Publish build information to IBM Cloud DevOps"; - } - - @Override - public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { - // To persist global configuration information, - // set that to properties and call save(). - environment = formData.getString("environment"); - debug_mode = Boolean.parseBoolean(formData.getString("debug_mode")); - save(); - return super.configure(req,formData); - } - - public String getEnvironment() { - return environment; - } - public boolean getDebugMode() { - return debug_mode; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/PublishDeploy.java b/src/main/java/com/ibm/devops/dra/PublishDeploy.java deleted file mode 100644 index f75b4d5..0000000 --- a/src/main/java/com/ibm/devops/dra/PublishDeploy.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardListBoxModel; -import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.gson.*; -import hudson.EnvVars; -import hudson.Extension; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Publisher; -import hudson.util.FormValidation; -import hudson.util.ListBoxModel; -import jenkins.model.Jenkins; -import jenkins.tasks.SimpleBuildStep; -import net.sf.json.JSONObject; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.kohsuke.stapler.*; - -import javax.annotation.Nonnull; -import javax.servlet.ServletException; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.TimeZone; - -public class PublishDeploy extends AbstractDevOpsAction implements SimpleBuildStep { - - private static String DEPLOYMENT_API_URL = "/organizations/{org_name}/toolchainids/{toolchain_id}/buildartifacts/{build_artifact}/builds/{build_id}/deployments"; - private final static String CONTENT_TYPE_JSON = "application/json"; - - private PrintStream printStream; - - // form fields from UI - private String applicationName; - private String toolchainName; - private String orgName; - private String buildJobName; - private String environmentName; - private String credentialsId; - private String applicationUrl; - private String buildNumber; - private static String bluemixToken; - private static String preCredentials; - - //fields to support jenkins pipeline - private String result; - private String username; - private String password; - - @DataBoundConstructor - public PublishDeploy(String applicationName, - String toolchainName, - String orgName, - String buildJobName, - String environmentName, - String credentialsId, - String applicationUrl, - OptionalBuildInfo additionalBuildInfo) { - this.applicationName = applicationName; - this.toolchainName = toolchainName; - this.orgName = orgName; - this.buildJobName = buildJobName; - this.environmentName = environmentName; - this.credentialsId = credentialsId; - this.applicationUrl = applicationUrl; - - if (additionalBuildInfo == null) { - this.buildNumber = null; - } else { - this.buildNumber = additionalBuildInfo.buildNumber; - } - } - - public PublishDeploy(String environmentName, - String applicationUrl, - String result, - String toolchainName, - String applicationName, - String orgName, - String username, - String password) { - this.environmentName = environmentName; - this.applicationName = applicationUrl; - this.result = result; - this.toolchainName = toolchainName; - this.applicationName = applicationName; - this.orgName = orgName; - this.username = username; - this.password = password; - } - - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - /** - * We'll use this from the config.jelly. - */ - public String getApplicationName() { - return applicationName; - } - - public String getToolchainName() { - return toolchainName; - } - - public String getOrgName() { - return orgName; - } - - public String getBuildJobName() { - return buildJobName; - } - - public String getEnvironmentName() { - return environmentName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getApplicationUrl() { - return applicationUrl; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getResult() { - return result; - } - - public static class OptionalBuildInfo { - private String buildNumber; - - @DataBoundConstructor - public OptionalBuildInfo(String buildNumber) { - this.buildNumber = buildNumber; - } - } - - @Override - public void perform(@Nonnull Run build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, - @Nonnull TaskListener listener) throws InterruptedException, IOException { - - printStream = listener.getLogger(); - printPluginVersion(this.getClass().getClassLoader(), printStream); - - // Get the project name and build id from environment - EnvVars envVars = build.getEnvironment(listener); - - if (!checkRootUrl(printStream)) { - return; - } - - // verify if user chooses advanced option to input customized DLMS - String env = getDescriptor().getEnvironment(); - String targetAPI = chooseTargetAPI(env); - String dlmsUrl = chooseDLMSUrl(env) + DEPLOYMENT_API_URL; - - // expand to support env vars - this.orgName = envVars.expand(this.orgName); - this.toolchainName = envVars.expand(this.toolchainName); - this.applicationName = envVars.expand(this.applicationName); - this.environmentName = envVars.expand(this.environmentName); - this.applicationUrl = envVars.expand(this.applicationUrl); - - if (Util.isNullOrEmpty(orgName) || Util.isNullOrEmpty(applicationName) || Util.isNullOrEmpty(environmentName) || Util.isNullOrEmpty(toolchainName)) { - printStream.println("[IBM Cloud DevOps] Missing few required configurations"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Deployment Info."); - return; - } - - String buildNumber; - // if user does not specify the build number - if (Util.isNullOrEmpty(this.buildNumber)) { - // locate the build job that triggers current build - Run triggeredBuild = getTriggeredBuild(build, buildJobName, envVars, printStream); - if (triggeredBuild == null) { - //failed to find the build job - return; - } else { - if (Util.isNullOrEmpty(this.buildJobName)) { - // handle the case which the build job name left empty, and the pipeline case - this.buildJobName = envVars.get("JOB_NAME"); - } - buildNumber = getBuildNumber(buildJobName, triggeredBuild); - } - } else { - buildNumber = envVars.expand(this.buildNumber); - } - - dlmsUrl = dlmsUrl.replace("{org_name}", URLEncoder.encode(this.orgName, "UTF-8").replaceAll("\\+", "%20")); - dlmsUrl = dlmsUrl.replace("{toolchain_id}", URLEncoder.encode(toolchainName, "UTF-8").replaceAll("\\+", "%20")); - dlmsUrl = dlmsUrl.replace("{build_artifact}", URLEncoder.encode(applicationName, "UTF-8").replaceAll("\\+", "%20")); - dlmsUrl = dlmsUrl.replace("{build_id}", URLEncoder.encode(buildNumber, "UTF-8").replaceAll("\\+", "%20")); - String link = chooseControlCenterUrl(env) + "deploymentrisk?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" + this.toolchainName; - String rootUrl = Jenkins.getInstance().getRootUrl(); - String jobUrl = rootUrl + build.getUrl(); - - String bluemixToken; - // get the Bluemix token - try { - if (Util.isNullOrEmpty(this.credentialsId)) { - bluemixToken = getBluemixToken(username, password, targetAPI); - } else { - bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); - } - - printStream.println("[IBM Cloud DevOps] Log in successfully, get the Bluemix token"); - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); - printStream.println("[IBM Cloud DevOps]" + e.toString()); - return; - } - - if (uploadDeploymentInfo(bluemixToken, dlmsUrl, build, jobUrl)) { - printStream.println("[IBM Cloud DevOps] Go to Control Center (" + link + ") to check your deployment status"); - } - } - - private boolean uploadDeploymentInfo(String token, String dlmsUrl, Run build, String jobUrl) { - - String resStr = ""; - - try { - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost postMethod = new HttpPost(dlmsUrl); - postMethod = addProxyInformation(postMethod); - postMethod.setHeader("Authorization", token); - postMethod.setHeader("Content-Type", CONTENT_TYPE_JSON); - - String buildStatus; - Result result = build.getResult(); - if ((result != null && result.equals(Result.SUCCESS)) - || (this.result != null && this.result.equals("SUCCESS"))) { - buildStatus = "pass"; - } else { - buildStatus = "fail"; - } - - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - dateFormat.setTimeZone(utc); - String timestamp = dateFormat.format(System.currentTimeMillis()); - - // build up the json body - Gson gson = new Gson(); - DeploymentInfoModel deploymentInfo = new DeploymentInfoModel(applicationUrl, environmentName, jobUrl, buildStatus, - timestamp); - - String json = gson.toJson(deploymentInfo); - StringEntity data = new StringEntity(json); - postMethod.setEntity(data); - CloseableHttpResponse response = httpClient.execute(postMethod); - resStr = EntityUtils.toString(response.getEntity()); - - - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - printStream.println("[IBM Cloud DevOps] Deployment Info uploaded successfully"); - return true; - - } else { - // if gets error status - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Deployment Info, response status " - + response.getStatusLine()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("user_error")) { - printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("user_error")); - } - } - } catch (JsonSyntaxException e) { - printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr); - } catch (IllegalStateException e) { - // will be triggered when 403 Forbidden - try { - printStream.println("[IBM Cloud DevOps] Please check if you have the access to " + URLEncoder.encode(this.orgName, "UTF-8") + " org"); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return false; - } - - @Override - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - // Overridden for better type safety. - // If your plugin doesn't really define any property on Descriptor, - // you don't have to do this. - @Override - public PublishDeploy.PublishDeployImpl getDescriptor() { - return (PublishDeploy.PublishDeployImpl) super.getDescriptor(); - } - - /** - * Descriptor for {@link PublishBuild}. Used as a singleton. The - * class is marked as public so that it can be accessed from views. - * - *

- * See - * src/main/resources/com/ibm/devops/dra/PublishBuild/*.jelly - * for the actual HTML fragment for the configuration screen. - */ - @Extension // This indicates to Jenkins that this is an implementation of an - // extension point. - public static final class PublishDeployImpl extends BuildStepDescriptor { - /** - * To persist global configuration information, simply store it in a - * field and call save(). - * - *

- * If you don't want fields to be persisted, use transient. - */ - - /** - * In order to load the persisted global configuration, you have to call - * load() in the constructor. - */ - public PublishDeployImpl() { - super(PublishDeploy.class); - load(); - } - - /** - * Performs on-the-fly validation of the form field 'credentialId'. - * - * @param value - * This parameter receives the value that the user has typed. - * @return Indicates the outcome of the validation. This is sent to the - * browser. - *

- * Note that returning {@link FormValidation#error(String)} does - * not prevent the form from being saved. It just means that a - * message will be displayed to the user. - */ - - private String environment; - private boolean debug_mode; - - public FormValidation doCheckOrgName(@QueryParameter String value) throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckApplicationName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckToolchainName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Could not retrieve list of toolchains. Please check your username and password. If you have not created a toolchain, create one here."); - } - return FormValidation.ok(); - } - - public FormValidation doCheckEnvironmentName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doTestConnection(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - preCredentials = credentialsId; - try { - String newToken = getBluemixToken(context, credentialsId, targetAPI); - if (Util.isNullOrEmpty(newToken)) { - bluemixToken = newToken; - return FormValidation.warning("Got empty token"); - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } catch (Exception e) { - return FormValidation.error("Failed to log in to Bluemix, please check your username/password"); - } - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } - - /** - * Autocompletion for build job name field - * - * @param value - * - user input for the build job name field - * @return - */ - public AutoCompletionCandidates doAutoCompleteBuildJobName(@QueryParameter String value) { - AutoCompletionCandidates auto = new AutoCompletionCandidates(); - - // get all jenkins job - List jobs = Jenkins.getInstance().getAllItems(Job.class); - for (int i = 0; i < jobs.size(); i++) { - String jobName = jobs.get(i).getName(); - - if (jobName.toLowerCase().startsWith(value.toLowerCase())) { - auto.add(jobName); - } - } - - return auto; - } - - /** - * This method is called to populate the credentials list on the Jenkins - * config page. - */ - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, - @QueryParameter("target") final String target) { - StandardListBoxModel result = new StandardListBoxModel(); - result.includeEmptyValue(); - result.withMatching(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), - CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, - URIRequirementBuilder.fromUri(target).build())); - return result; - } - - /** - * This method is called to populate the toolchain list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillToolchainNameItems(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId, - @QueryParameter("orgName") final String orgName) { - String targetAPI = chooseTargetAPI(environment); - try { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######UPLOAD DEPLOYMENT INFO : calling getToolchainList#######"); - } - ListBoxModel toolChainListBox = getToolchainList(bluemixToken, orgName, environment, debug_mode); - return toolChainListBox; - } - - /** - * Required Method This is used to determine if this build step is - * applicable for your chosen project type. (FreeStyle, - * MultiConfiguration, Maven) Some plugin build steps might be made to - * be only available to MultiConfiguration projects. - * - * @param aClass - * The current project - * @return a boolean indicating whether this build step can be chose - * given the project type - */ - public boolean isApplicable(Class aClass) { - // Indicates that this builder can be used with all kinds of project - // types - // return FreeStyleProject.class.isAssignableFrom(aClass); - return true; - } - - /** - * Required Method - * - * @return The text to be displayed when selecting your build in the - * project - */ - public String getDisplayName() { - return "Publish deployment information to IBM Cloud DevOps"; - } - - @Override - public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { - // To persist global configuration information, - // set that to properties and call save(). - environment = formData.getString("environment"); - debug_mode = Boolean.parseBoolean(formData.getString("debug_mode")); - save(); - return super.configure(req, formData); - } - - public String getEnvironment() { - return environment; - } - public boolean getDebugMode() { - return debug_mode; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/PublishSQ.java b/src/main/java/com/ibm/devops/dra/PublishSQ.java deleted file mode 100644 index b74cc12..0000000 --- a/src/main/java/com/ibm/devops/dra/PublishSQ.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardListBoxModel; -import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.gson.*; -import hudson.*; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Publisher; -import hudson.util.FormValidation; -import hudson.util.ListBoxModel; -import jenkins.model.Jenkins; -import jenkins.tasks.SimpleBuildStep; -import net.sf.json.JSONObject; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.entity.StringEntity; -import org.kohsuke.stapler.*; - -import javax.annotation.Nonnull; -import javax.servlet.ServletException; -import java.io.*; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - - -import javax.xml.bind.DatatypeConverter; - -/** - * Authenticate with Bluemix and then upload the result file to DRA - */ -public class PublishSQ extends AbstractDevOpsAction implements SimpleBuildStep { - - private final static String API_PART = "/organizations/{org_name}/toolchainids/{toolchain_id}/buildartifacts/{build_artifact}/builds/{build_id}/results"; - private final static String CONTENT_TYPE_JSON = "application/json"; - - // form fields from UI - private String applicationName; - private String buildJobName; - private String orgName; - private String toolchainName; - private String environmentName; - private String credentialsId; - private String buildNumber; - - private String SQProjectKey; - private String SQHostName; - private String SQAuthToken; - private String IBMusername; - private String IBMpassword; - - private String envName; - private boolean isDeploy; - - private PrintStream printStream; - private String dlmsUrl; - private static String bluemixToken; - private static String preCredentials; - - @DataBoundConstructor - public PublishSQ(String credentialsId, - String orgName, - String toolchainName, - String buildJobName, - String applicationName, - String SQHostName, - String SQAuthToken, - String SQProjectKey, - OptionalBuildInfo additionalBuildInfo) { - this.credentialsId = credentialsId; - this.orgName = orgName; - this.toolchainName = toolchainName; - this.buildJobName = buildJobName; - this.applicationName = applicationName; - this.SQHostName = SQHostName; - this.SQAuthToken = SQAuthToken; - this.SQProjectKey = SQProjectKey; - - if (additionalBuildInfo == null) { - this.buildNumber = null; - } else { - this.buildNumber = additionalBuildInfo.buildNumber; - } - } - - public PublishSQ(String orgName, - String applicationName, - String toolchainName, - String SQProjectKey, - String SQHostName, - String SQAuthToken, - String IBMusername, - String IBMpassword) { - this.orgName = orgName; - this.applicationName = applicationName; - this.toolchainName = toolchainName; - this.SQProjectKey = SQProjectKey; - this.SQHostName = SQHostName; - this.SQAuthToken = SQAuthToken; - this.IBMusername = IBMusername; - this.IBMpassword = IBMpassword; - } - - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - /** - * We'll use this from the config.jelly. - */ - public String getApplicationName() { - return applicationName; - } - - public String getToolchainName() { - return toolchainName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getBuildJobName() { - return buildJobName; - } - - public String getSQHostName() { - return this.SQHostName; - } - - public String getSQAuthToken() { - return this.SQAuthToken; - } - - public String getSQProjectKey() { - return this.SQProjectKey; - } - - public String getBuildNumber() { - return buildNumber; - } - - public boolean isDeploy() { - return isDeploy; - } - - public static class OptionalBuildInfo { - private String buildNumber; - - @DataBoundConstructor - public OptionalBuildInfo(String buildNumber) { - this.buildNumber = buildNumber; - } - } - - - @Override - public void perform(@Nonnull Run build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { - - printStream = listener.getLogger(); - printPluginVersion(this.getClass().getClassLoader(), printStream); - - // Get the project name and build id from environment - EnvVars envVars = build.getEnvironment(listener); - - // verify if user chooses advanced option to input customized DLMS - String env = getDescriptor().getEnvironment(); - String targetAPI = chooseTargetAPI(env); - String url = chooseDLMSUrl(env) + API_PART; - // expand to support env vars - this.orgName = envVars.expand(this.orgName); - this.applicationName = envVars.expand(this.applicationName); - this.toolchainName = envVars.expand(this.toolchainName); - if (this.isDeploy || !Util.isNullOrEmpty(this.envName)) { - this.environmentName = envVars.expand(this.envName); - } - - String buildNumber; - // if user does not specify the build number - if (Util.isNullOrEmpty(this.buildNumber)) { - // locate the build job that triggers current build - Run triggeredBuild = getTriggeredBuild(build, buildJobName, envVars, printStream); - if (triggeredBuild == null) { - //failed to find the build job - return; - } else { - if (Util.isNullOrEmpty(this.buildJobName)) { - // handle the case which the build job name left empty, and the pipeline case - this.buildJobName = envVars.get("JOB_NAME"); - } - buildNumber = getBuildNumber(buildJobName, triggeredBuild); - } - } else { - buildNumber = envVars.expand(this.buildNumber); - } - - url = url.replace("{org_name}", URLEncoder.encode(this.orgName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{toolchain_id}", URLEncoder.encode(this.toolchainName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{build_artifact}", URLEncoder.encode(this.applicationName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{build_id}", URLEncoder.encode(buildNumber, "UTF-8").replaceAll("\\+", "%20")); - this.dlmsUrl = url; - - String bluemixToken; - // get the Bluemix token - try { - if (Util.isNullOrEmpty(this.credentialsId)) { - bluemixToken = getBluemixToken(IBMusername, IBMpassword, targetAPI); - } else { - bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); - } - printStream.println("[IBM Cloud DevOps] Log in successfully, got the Bluemix token"); - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); - printStream.println("[IBM Cloud DevOps]" + e.toString()); - return; - } - - Map headers = new HashMap(); - // ':' needs to be added so the SQ api knows an auth token is being used - String SQAuthToken = DatatypeConverter.printBase64Binary((this.SQAuthToken + ":").getBytes("UTF-8")); - headers.put("Authorization", "Basic " + SQAuthToken); - try { - JsonObject SQqualityGate = sendGETRequest(this.SQHostName + "/api/qualitygates/project_status?projectKey=" + this.SQProjectKey, headers); - printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for quality gate information"); - JsonObject SQissues = sendGETRequest(this.SQHostName + "/api/issues/search?statuses=OPEN&componentKeys=" + this.SQProjectKey, headers); - printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for issue information"); - JsonObject SQratings = sendGETRequest(this.SQHostName + "/api/measures/component?metricKeys=reliability_rating,security_rating,sqale_rating&componentKey=" + this.SQProjectKey, headers); - printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for metric information"); - - JsonObject payload = createDLMSPayload(SQqualityGate, SQissues, SQratings); - JsonArray urls = createPayloadUrls(this.SQHostName, this.SQProjectKey); - sendPayloadToDLMS(bluemixToken, payload, urls); - - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Error: Unable to upload results. Please make sure all parameters are valid"); - e.printStackTrace(); - } - } - - /** - * Constructs the urls that should be sent with the DLMS message - * - * @param SQHostname hostname of the SQ instance - * @param SQKey project key of the SQ instance - * @return an array of URLs that should be sent to dlms along with the payload - */ - public JsonArray createPayloadUrls(String SQHostname, String SQKey) { - - JsonArray urls = new JsonArray(); - String url = SQHostname + "/dashboard/index/" + SQKey; - urls.add(url); - return urls; - } - - /** - * Combines all SQ information into one gson that can be sent to DLMS - * - * @param qualityGateData information pertaining to SQ gate status - * @param issuesData information pertaining to SQ issues raised - * @param ratingsData information pertaining to SQ ratings - * @return combined gson object - */ - public JsonObject createDLMSPayload(JsonObject qualityGateData, JsonObject issuesData, JsonObject ratingsData) { - - JsonObject payload = new JsonObject(); - - payload.add("qualityGate", qualityGateData.get("projectStatus")); - payload.add("issues", issuesData.get("issues")); - - JsonParser parser = new JsonParser(); - JsonObject component = (JsonObject)parser.parse(ratingsData.get("component").toString()); - payload.add("ratings", component.get("measures")); - - return payload; - } - - /** - * Sends a GET request to the provided url - * - * @param url the endpoint of the request - * @param headers a map of headers where key is the header name and the map value is the header value - * @return a JSON parsed representation of the payload returneds - * @throws Exception - */ - private JsonObject sendGETRequest(String url, Map headers) throws Exception { - - String resStr; - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpGet getMethod = new HttpGet(url); - getMethod = addProxyInformation(getMethod); - - //add request headers - for(Map.Entry entry: headers.entrySet()) { - getMethod.setHeader(entry.getKey(), entry.getValue()); - } - - CloseableHttpResponse response = httpClient.execute(getMethod); - resStr = EntityUtils.toString(response.getEntity()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - - return resJson; - } - - /** - * Sends POST method to DLMS to upload SQ results - *F - * @param bluemixToken the bluemix auth header that allows us to talk to dlms - * @param payload the content part of the payload to send to dlms - * @param urls a json array that holds the urls for a payload - * @return boolean based on if the request was successful or not - */ - private boolean sendPayloadToDLMS(String bluemixToken, JsonObject payload, JsonArray urls) { - String resStr = ""; - printStream.println("[IBM Cloud DevOps] Uploading SonarQube results..."); - try { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost postMethod = new HttpPost(this.dlmsUrl); - postMethod = addProxyInformation(postMethod); - postMethod.setHeader("Authorization", bluemixToken); - postMethod.setHeader("Content-Type", CONTENT_TYPE_JSON); - - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - dateFormat.setTimeZone(utc); - String timestamp = dateFormat.format(System.currentTimeMillis()); - - JsonObject body = new JsonObject(); - - body.addProperty("contents", DatatypeConverter.printBase64Binary(payload.toString().getBytes("UTF-8"))); - body.addProperty("contents_type", CONTENT_TYPE_JSON); - body.addProperty("timestamp", timestamp); - body.addProperty("tool_name", "sonarqube"); - body.addProperty("lifecycle_stage", "sonarqube"); - body.add("url", urls); - - StringEntity data = new StringEntity(body.toString()); - postMethod.setEntity(data); - CloseableHttpResponse response = httpClient.execute(postMethod); - resStr = EntityUtils.toString(response.getEntity()); - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - printStream.println("[IBM Cloud DevOps] Upload Build Information successfully"); - return true; - - } else { - // if gets error status - printStream.println("[IBM Cloud DevOps] Error: Failed to upload, response status " + response.getStatusLine()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("user_error")) { - printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("user_error")); - } - } - } catch (JsonSyntaxException e) { - printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr); - } catch (IllegalStateException e) { - // will be triggered when 403 Forbidden - try { - printStream.println("[IBM Cloud DevOps] Please check if you have the access to " + URLEncoder.encode(this.orgName, "UTF-8") + " org"); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - @Override - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - // Overridden for better type safety. - // If your plugin doesn't really define any property on Descriptor, - // you don't have to do this. - @Override - public PublishSQ.PublishTestImpl getDescriptor() { - return (PublishSQ.PublishTestImpl)super.getDescriptor(); - } - - /** - * Descriptor for {@link PublishSQ}. Used as a singleton. - * The class is marked as public so that it can be accessed from views. - * - *

- * See src/main/resources/com/ibm/devops/dra/PublishTest/*.jelly - * for the actual HTML fragment for the configuration screen. - */ - @Extension // This indicates to Jenkins that this is an implementation of an extension point. - public static final class PublishTestImpl extends BuildStepDescriptor { - /** - * To persist global configuration information, - * simply store it in a field and call save(). - * - *

- * If you don't want fields to be persisted, use transient. - */ - - /** - * In order to load the persisted global configuration, you have to - * call load() in the constructor. - */ - public PublishTestImpl() { - super(PublishSQ.class); - load(); - } - - /** - * Performs on-the-fly validation of the form field 'credentialId'. - * - * @param value - * This parameter receives the value that the user has typed. - * @return - * Indicates the outcome of the validation. This is sent to the browser. - *

- * Note that returning {@link FormValidation#error(String)} does not - * prevent the form from being saved. It just means that a message - * will be displayed to the user. - */ - - private String environment; - private boolean debug_mode; - - public FormValidation doCheckOrgName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckToolchainName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Could not retrieve list of toolchains. Please check your username and password. If you have not created a toolchain, create one here."); - } - return FormValidation.ok(); - } - - public FormValidation doCheckApplicationName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckSQHostName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckSQAuthToken(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckSQProjectKey(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doTestConnection(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - preCredentials = credentialsId; - try { - String newToken = getBluemixToken(context, credentialsId, targetAPI); - if (Util.isNullOrEmpty(newToken)) { - bluemixToken = newToken; - return FormValidation.warning("Got empty token"); - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } catch (Exception e) { - return FormValidation.error("Failed to log in to Bluemix, please check your username/password"); - } - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } - - /** - * This method is called to populate the credentials list on the Jenkins config page. - */ - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, - @QueryParameter("target") final String target) { - StandardListBoxModel result = new StandardListBoxModel(); - result.includeEmptyValue(); - result.withMatching(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), - CredentialsProvider.lookupCredentials( - StandardUsernameCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(target).build() - ) - ); - return result; - } - - /** - * This method is called to populate the toolchain list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillToolchainNameItems(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId, - @QueryParameter("orgName") final String orgName) { - String targetAPI = chooseTargetAPI(environment); - try { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######UPLOAD BUILD INFO : calling getToolchainList#######"); - } - ListBoxModel toolChainListBox = getToolchainList(bluemixToken, orgName, environment, debug_mode); - return toolChainListBox; - - } - - /** - * Required Method - * This is used to determine if this build step is applicable for your chosen project type. (FreeStyle, MultiConfiguration, Maven) - * Some plugin build steps might be made to be only available to MultiConfiguration projects. - * - * @param aClass The current project - * @return a boolean indicating whether this build step can be chose given the project type - */ - public boolean isApplicable(Class aClass) { - // Indicates that this builder can be used with all kinds of project types - // return FreeStyleProject.class.isAssignableFrom(aClass); - return true; - } - - /** - * Required Method - * @return The text to be displayed when selecting your build in the project - */ - public String getDisplayName() { - return "Publish SonarQube test result to IBM Cloud DevOps"; - } - - @Override - public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { - // To persist global configuration information, - // set that to properties and call save(). - environment = formData.getString("environment"); - debug_mode = Boolean.parseBoolean(formData.getString("debug_mode")); - save(); - return super.configure(req,formData); - } - - public String getEnvironment() { - return environment; - } - public boolean getDebugMode() { - return debug_mode; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/PublishTest.java b/src/main/java/com/ibm/devops/dra/PublishTest.java deleted file mode 100644 index 94633a6..0000000 --- a/src/main/java/com/ibm/devops/dra/PublishTest.java +++ /dev/null @@ -1,974 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.StandardListBoxModel; -import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; -import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; -import com.google.gson.*; -import hudson.*; -import hudson.model.*; -import hudson.security.ACL; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Publisher; -import hudson.util.FormValidation; -import hudson.util.ListBoxModel; -import jenkins.model.Jenkins; -import jenkins.tasks.SimpleBuildStep; -import net.sf.json.JSONObject; -import org.apache.commons.io.FilenameUtils; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.kohsuke.stapler.*; - -import javax.annotation.Nonnull; -import javax.servlet.ServletException; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.Serializable; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.TimeZone; -import java.util.HashSet; - -/** - * Authenticate with Bluemix and then upload the result file to DRA - */ -public class PublishTest extends AbstractDevOpsAction implements SimpleBuildStep { - - private final static String API_PART = "/organizations/{org_name}/toolchainids/{toolchain_id}/buildartifacts/{build_artifact}/builds/{build_id}/results_multipart"; - private final static String CONTENT_TYPE_JSON = "application/json"; - private final static String CONTENT_TYPE_XML = "application/xml"; - - // form fields from UI - private final String lifecycleStage; - private String contents; - private String additionalLifecycleStage; - private String additionalContents; - private String buildNumber; - private String applicationName; - private String buildJobName; - private String orgName; - private String toolchainName; - private String environmentName; - private String credentialsId; - private String policyName; - private boolean willDisrupt; - - private EnvironmentScope testEnv; - private String envName; - private boolean isDeploy; - - private PrintStream printStream; - private File root; - private String dlmsUrl; - private String draUrl; - private static String bluemixToken; - private static String preCredentials; - - //fields to support jenkins pipeline - private String username; - private String password; - - @DataBoundConstructor - public PublishTest(String lifecycleStage, - String contents, - String applicationName, - String orgName, - String toolchainName, - String buildJobName, - String credentialsId, - OptionalUploadBlock additionalUpload, - OptionalBuildInfo additionalBuildInfo, - OptionalGate additionalGate, - EnvironmentScope testEnv) { - this.lifecycleStage = lifecycleStage; - this.contents = contents; - this.credentialsId = credentialsId; - this.applicationName = applicationName; - this.orgName = orgName; - this.toolchainName = toolchainName; - this.buildJobName = buildJobName; - this.testEnv = testEnv; - this.envName = testEnv.getEnvName(); - this.isDeploy = testEnv.isDeploy(); - - if (additionalUpload == null) { - this.additionalContents = null; - this.additionalLifecycleStage = null; - } else { - this.additionalLifecycleStage = additionalUpload.additionalLifecycleStage; - this.additionalContents = additionalUpload.additionalContents; - } - - if (additionalBuildInfo == null) { - this.buildNumber = null; - } else { - this.buildNumber = additionalBuildInfo.buildNumber; - } - - if (additionalGate == null) { - this.policyName = null; - this.willDisrupt = false; - } else { - this.policyName = additionalGate.getPolicyName(); - this.willDisrupt = additionalGate.isWillDisrupt(); - } - } - - public PublishTest(String lifecycleStage, - String contents, - String envName, - String orgName, - String applicationName, - String toolchainName, - String username, - String password) { - this.lifecycleStage = lifecycleStage; - this.contents = contents; - this.envName = envName; - this.applicationName = applicationName; - this.orgName = orgName; - this.toolchainName = toolchainName; - this.username = username; - this.password = password; - } - - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - /** - * We'll use this from the config.jelly. - */ - public String getApplicationName() { - return applicationName; - } - - public String getToolchainName() { - return toolchainName; - } - - public String getOrgName() { - return orgName; - } - - public String getEnvironmentName() { - return environmentName; - } - - public String getBuildJobName() { - return buildJobName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getLifecycleStage() { - return lifecycleStage; - } - - public String getContents() { - return contents; - } - - public String getAdditionalLifecycleStage() { - return additionalLifecycleStage; - } - - public String getAdditionalContents() { - return additionalContents; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getPolicyName() { - return policyName; - } - - public boolean isWillDisrupt() { - return willDisrupt; - } - - public EnvironmentScope getTestEnv() { - return testEnv; - } - - public String getEnvName() { - return envName; - } - - public boolean isDeploy() { - return isDeploy; - } - - /** - * Sub class for Optional Upload Block - */ - public static class OptionalUploadBlock { - private String additionalLifecycleStage; - private String additionalContents; - - @DataBoundConstructor - public OptionalUploadBlock(String additionalLifecycleStage, String additionalContents) { - this.additionalLifecycleStage = additionalLifecycleStage; - this.additionalContents = additionalContents; - } - } - - public static class OptionalBuildInfo { - private String buildNumber; - - @DataBoundConstructor - public OptionalBuildInfo(String buildNumber) { - this.buildNumber = buildNumber; - } - } - - public static class OptionalGate { - private String policyName; - private boolean willDisrupt; - - @DataBoundConstructor - public OptionalGate(String policyName, boolean willDisrupt) { - this.policyName = policyName; - setWillDisrupt(willDisrupt); - } - - public String getPolicyName() { - return policyName; - } - - public boolean isWillDisrupt() { - return willDisrupt; - } - - @DataBoundSetter - public void setWillDisrupt(boolean willDisrupt) { - this.willDisrupt = willDisrupt; - } - } - - - @Override - public void perform(@Nonnull Run build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { - - printStream = listener.getLogger(); - printPluginVersion(this.getClass().getClassLoader(), printStream); - - // create root dir for storing test result - root = new File(build.getRootDir(), "DRA_TestResults"); - - // Get the project name and build id from environment - EnvVars envVars = build.getEnvironment(listener); - - if (!checkRootUrl(printStream)) { - return; - } - - // verify if user chooses advanced option to input customized DLMS - String env = getDescriptor().getEnvironment(); - String targetAPI = chooseTargetAPI(env); - String url = chooseDLMSUrl(env) + API_PART; - // expand to support env vars - this.orgName = envVars.expand(this.orgName); - this.applicationName = envVars.expand(this.applicationName); - this.toolchainName = envVars.expand(this.toolchainName); - this.contents = envVars.expand(this.contents); - if (this.isDeploy || !Util.isNullOrEmpty(this.envName)) { - this.environmentName = envVars.expand(this.envName); - } - - String buildNumber, buildUrl; - // if user does not specify the build number - if (Util.isNullOrEmpty(this.buildNumber)) { - // locate the build job that triggers current build - Run triggeredBuild = getTriggeredBuild(build, buildJobName, envVars, printStream); - if (triggeredBuild == null) { - //failed to find the build job - return; - } else { - if (Util.isNullOrEmpty(this.buildJobName)) { - // handle the case which the build job name left empty, and the pipeline case - this.buildJobName = envVars.get("JOB_NAME"); - } - buildNumber = getBuildNumber(buildJobName, triggeredBuild); - } - } else { - buildNumber = envVars.expand(this.buildNumber); - } - - url = url.replace("{org_name}", URLEncoder.encode(this.orgName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{toolchain_id}", URLEncoder.encode(this.toolchainName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{build_artifact}", URLEncoder.encode(this.applicationName, "UTF-8").replaceAll("\\+", "%20")); - url = url.replace("{build_id}", URLEncoder.encode(buildNumber, "UTF-8").replaceAll("\\+", "%20")); - this.dlmsUrl = url; - - String link = chooseControlCenterUrl(env) + "deploymentrisk?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" + this.toolchainName; - - String bluemixToken; - // get the Bluemix token - try { - if (Util.isNullOrEmpty(this.credentialsId)) { - bluemixToken = getBluemixToken(username, password, targetAPI); - } else { - bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); - } - - printStream.println("[IBM Cloud DevOps] Log in successfully, get the Bluemix token"); - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); - printStream.println("[IBM Cloud DevOps]" + e.toString()); - return; - } - - // parse the wildcard result files - try { - if(!scanAndUpload(build, workspace, contents, lifecycleStage, bluemixToken)){ - // if there is any error when scanning and uploading - return; - } - - // check to see if we need to upload additional result file - if (!Util.isNullOrEmpty(additionalContents) && !Util.isNullOrEmpty(additionalLifecycleStage)) { - if(!scanAndUpload(build, workspace, additionalContents, additionalLifecycleStage, bluemixToken)) { - return; - } - } - } catch (Exception e) { - printStream.print("[IBM Cloud DevOps] Got Exception: " + e.getMessage()); - e.printStackTrace(); - return; - } - - printStream.println("[IBM Cloud DevOps] Go to Control Center (" + link + ") to check your build status"); - - // Gate - // verify if user chooses advanced option to input customized DRA - if (Util.isNullOrEmpty(policyName)) { - return; - } - - this.draUrl = chooseDRAUrl(env); - - // get decision response from DRA - try { - JsonObject decisionJson = getDecisionFromDRA(bluemixToken, buildNumber); - if (decisionJson == null) { - printStream.println("[IBM Cloud DevOps] get empty decision"); - return; - } - - // retrieve the decision id to compose the report link - String decisionId = String.valueOf(decisionJson.get("decision_id")); - // remove the double quotes - decisionId = decisionId.replace("\"",""); - - // Show Proceed or Failed based on the decision - String decision = String.valueOf(decisionJson.get("contents").getAsJsonObject().get("proceed")); - if (decision.equals("true")) { - decision = "Succeed"; - } else { - decision = "Failed"; - } - - String cclink = chooseControlCenterUrl(env) + "deploymentrisk?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" + this.toolchainName; - - String reportUrl = chooseReportUrl(env) + "decisionreport?orgName=" + URLEncoder.encode(this.orgName, "UTF-8") + "&toolchainId=" - + URLEncoder.encode(toolchainName, "UTF-8") + "&reportId=" + decisionId; - GatePublisherAction action = new GatePublisherAction(reportUrl, cclink, decision, this.policyName, build); - build.addAction(action); - - printStream.println("************************************"); - printStream.println("Check IBM Cloud DevOps Gate Evaluation report here -" + reportUrl); - printStream.println("Check IBM Cloud DevOps Deployment Risk Dashboard here -" + cclink); - // console output for a "fail" decision - if (decision.equals("Failed")) { - printStream.println("IBM Cloud DevOps decision to proceed is: false"); - printStream.println("************************************"); - if (willDisrupt) { - Result result = Result.FAILURE; - build.setResult(result); - } - return; - } - - // console output for a "proceed" decision - printStream.println("IBM Cloud DevOps decision to proceed is: true"); - printStream.println("************************************"); - return; - - } catch (IOException e) { - printStream.print("[IBM Cloud DevOps] Error: " + e.getMessage()); - } - - } - - @Override - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - /** - * Support wildcard for the result file path, scan the path and upload each matching result file to the DLMS - * @param build - the current build - * @param bluemixToken - the Bluemix toekn - * @return false if there is any error when scan and upload the file - */ - public boolean scanAndUpload(Run build, FilePath workspace, String path, String lifecycleStage, String bluemixToken) throws Exception { - boolean errorFlag = true; - FilePath[] filePaths = null; - - if (Util.isNullOrEmpty(path)) { - // if no result file specified, create dummy result based on the build status - filePaths = new FilePath[]{createDummyFile(build, workspace)}; - } else { - - // remove "./" prefix of the path if it exists - if (path.startsWith("./")) { - path = path.substring(2); - } - - try { - filePaths = workspace.list(path); - } catch(InterruptedException ie) { - printStream.println("[IBM Cloud DevOps] catching interrupt" + ie.getMessage()); - ie.printStackTrace(); - throw ie; - } catch (IOException e) { - printStream.println("[IBM Cloud DevOps] catching act" + e.getMessage()); - e.printStackTrace(); - throw e; - } - } - - if (filePaths == null || filePaths.length < 1) { - printStream.println("[IBM Cloud DevOps] Error: Fail to find the file, please check the path"); - return false; - } else { - - for (FilePath fp : filePaths) { - - // make sure the file path is for file, and copy to the master build folder - if (!fp.isDirectory()) { - FilePath resultFileLocation = new FilePath(new File(root, fp.getName())); - fp.copyTo(resultFileLocation); - } - - //get timestamp - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - dateFormat.setTimeZone(utc); - String timestamp = dateFormat.format(System.currentTimeMillis()); - - String rootUrl = Jenkins.getInstance().getRootUrl(); - String jobUrl = rootUrl + build.getUrl(); - - // upload the result file to DLMS - String res = sendFormToDLMS(bluemixToken, fp, lifecycleStage, jobUrl, timestamp); - if(!printUploadMessage(res, fp.getName())) { - errorFlag = false; - } - } - } - - return errorFlag; - } - - /** - * create a dummy result file following mocha format for some testing which does not generate test report - * @param build - current build - * @param workspace - current workspace, if it runs on slave, then it will be the path on slave - * @return simple test result file - */ - private FilePath createDummyFile(Run build, FilePath workspace) throws Exception { - - // if user did not specify the result file location, upload the dummy json file - Gson gson = new Gson(); - - //set the passes and failures based on the test status - int passes, failures; - Result result = build.getResult(); - if (result != null) { - if (!result.equals(Result.SUCCESS)) { - passes = 0; - failures = 1; - } else { - passes = 1; - failures = 0; - } - } else { - throw new Exception("Failed to get build result"); - } - - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - dateFormat.setTimeZone(utc); - String start = dateFormat.format(build.getStartTimeInMillis()); - long duration = build.getDuration(); - String end = dateFormat.format(build.getStartTimeInMillis() + duration); - - TestResultModel.Stats stats = new TestResultModel.Stats(1, 1, passes, 0, failures, start, end, duration); - TestResultModel.Test test = new TestResultModel.Test("unknown test", "unknown test", duration, 0, null); - TestResultModel.Test[] tests = {test}; - String[] emptyArray = {}; - TestResultModel testResultModel = new TestResultModel(stats, tests, emptyArray, emptyArray, emptyArray); - - // create new dummy file - try { - FilePath filePath = workspace.child("simpleTest.json"); - filePath.write(gson.toJson(testResultModel), "UTF8"); - return filePath; - } catch (IOException e) { - printStream.println("[IBM Cloud DevOps] Failed to create dummy file in current workspace, Exception: " + e.getMessage()); - } - - return null; - } - - /** - * print out the response message from DLMS to the console log - * @param response - response from DLMS - * @param fileName - uploaded filename - * @return true if upload succeed, otherwise return false - */ - private boolean printUploadMessage(String response, String fileName) { - if (response.contains("Error")) { - printStream.println("[IBM Cloud DevOps] " + response); - } else if (response.contains("200")) { - printStream.println("[IBM Cloud DevOps] Upload [" + fileName + "] SUCCESSFUL"); - return true; - } else { - printStream.println("[IBM Cloud DevOps]" + response + ", Upload [" + fileName + "] FAILED"); - } - - return false; - } - - /** - * * Send POST request to DLMS back end with the result file - * @param bluemixToken - the Bluemix token - * @param contents - the result file - * @param jobUrl - the build url of the build job in Jenkins - * @param timestamp - * @return - response/error message from DLMS - */ - public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException { - - // create http client and post method - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost postMethod = new HttpPost(this.dlmsUrl); - - postMethod = addProxyInformation(postMethod); - // build up multi-part forms - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if (contents != null) { - - File file = new File(root, contents.getName()); - FileBody fileBody = new FileBody(file); - builder.addPart("contents", fileBody); - - - builder.addTextBody("test_artifact", file.getName()); - if (this.isDeploy) { - builder.addTextBody("environment_name", environmentName); - } - //Todo check the value of lifecycleStage - builder.addTextBody("lifecycle_stage", lifecycleStage); - builder.addTextBody("url", jobUrl); - builder.addTextBody("timestamp", timestamp); - - String fileExt = FilenameUtils.getExtension(contents.getName()); - String contentType; - switch (fileExt) { - case "json": - contentType = CONTENT_TYPE_JSON; - break; - case "xml": - contentType = CONTENT_TYPE_XML; - break; - default: - return "Error: " + contents.getName() + " is an invalid result file type"; - } - - builder.addTextBody("contents_type", contentType); - HttpEntity entity = builder.build(); - postMethod.setEntity(entity); - postMethod.setHeader("Authorization", bluemixToken); - } else { - return "Error: File is null"; - } - - - CloseableHttpResponse response = null; - try { - response = httpClient.execute(postMethod); - // parse the response json body to display detailed info - String resStr = EntityUtils.toString(response.getEntity()); - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - - if (!element.isJsonObject()) { - // 401 Forbidden - return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString(); - } else { - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("status")) { - return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status"); - } else { - // other cases - return String.valueOf(response.getStatusLine()); - } - } - } catch (IOException e) { - e.printStackTrace(); - throw e; - } - } - - - /** - * Send a request to DRA backend to get a decision - * @param buildId - build ID, get from Jenkins environment - * @return - the response decision Json file - */ - private JsonObject getDecisionFromDRA(String bluemixToken, String buildId) throws IOException { - // create http client and post method - CloseableHttpClient httpClient = HttpClients.createDefault(); - - String url = this.draUrl; - url = url + "/organizations/" + orgName + - "/toolchainids/" + toolchainName + - "/buildartifacts/" + URLEncoder.encode(applicationName, "UTF-8").replaceAll("\\+", "%20") + - "/builds/" + buildId + - "/policies/" + URLEncoder.encode(policyName, "UTF-8").replaceAll("\\+", "%20") + - "/decisions"; - if (this.isDeploy) { - url = url.concat("?environment_name=" + environmentName); - } - - HttpPost postMethod = new HttpPost(url); - - postMethod = addProxyInformation(postMethod); - postMethod.setHeader("Authorization", bluemixToken); - postMethod.setHeader("Content-Type", CONTENT_TYPE_JSON); - - CloseableHttpResponse response = httpClient.execute(postMethod); - String resStr = EntityUtils.toString(response.getEntity()); - - try { - if (response.getStatusLine().toString().contains("200")) { - // get 200 response - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - printStream.println("[IBM Cloud DevOps] Get decision successfully"); - return resJson; - } else { - // if gets error status - printStream.println("[IBM Cloud DevOps] Error: Failed to get a decision, response status " + response.getStatusLine()); - - JsonParser parser = new JsonParser(); - JsonElement element = parser.parse(resStr); - JsonObject resJson = element.getAsJsonObject(); - if (resJson != null && resJson.has("message")) { - printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("message")); - } - } - } catch (JsonSyntaxException e) { - printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr); - } - - return null; - - } - - // Overridden for better type safety. - // If your plugin doesn't really define any property on Descriptor, - // you don't have to do this. - @Override - public PublishTest.PublishTestImpl getDescriptor() { - return (PublishTest.PublishTestImpl)super.getDescriptor(); - } - - /** - * Descriptor for {@link PublishTest}. Used as a singleton. - * The class is marked as public so that it can be accessed from views. - * - *

- * See src/main/resources/com/ibm/devops/dra/PublishTest/*.jelly - * for the actual HTML fragment for the configuration screen. - */ - @Extension // This indicates to Jenkins that this is an implementation of an extension point. - public static final class PublishTestImpl extends BuildStepDescriptor { - /** - * To persist global configuration information, - * simply store it in a field and call save(). - * - *

- * If you don't want fields to be persisted, use transient. - */ - - /** - * In order to load the persisted global configuration, you have to - * call load() in the constructor. - */ - public PublishTestImpl() { - super(PublishTest.class); - load(); - } - - /** - * Performs on-the-fly validation of the form field 'credentialId'. - * - * @param value - * This parameter receives the value that the user has typed. - * @return - * Indicates the outcome of the validation. This is sent to the browser. - *

- * Note that returning {@link FormValidation#error(String)} does not - * prevent the form from being saved. It just means that a message - * will be displayed to the user. - */ - - private String environment; - private boolean debug_mode; - - public FormValidation doCheckOrgName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckApplicationName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckToolchainName(@QueryParameter String value) - throws IOException, ServletException { - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Could not retrieve list of toolchains. Please check your username and password. If you have not created a toolchain, create one here."); - } - return FormValidation.ok(); - } - - public FormValidation doCheckEnvironmentName(@QueryParameter String value) - throws IOException, ServletException { - return FormValidation.validateRequired(value); - } - - public FormValidation doCheckPolicyName(@QueryParameter String value) { - - if (value == null || value.equals("empty")) { - return FormValidation.errorWithMarkup("Fail to get the policies, please check your username/password or org name and make sure you have created policies for this org and toolchain."); - } - return FormValidation.ok(); - } - - public FormValidation doTestConnection(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - preCredentials = credentialsId; - try { - String bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - if (Util.isNullOrEmpty(bluemixToken)) { - PublishTest.bluemixToken = bluemixToken; - return FormValidation.warning("Got empty token"); - } else { - return FormValidation.okWithMarkup("Connection successful"); - } - } catch (Exception e) { - return FormValidation.error("Failed to log in to Bluemix, please check your username/password"); - } - } else { - - return FormValidation.okWithMarkup("Connection successful"); - } - } - - /** - * Autocompletion for build job name field - * @param value - user input for the build job name field - * @return - */ - public AutoCompletionCandidates doAutoCompleteBuildJobName(@QueryParameter String value) { - AutoCompletionCandidates auto = new AutoCompletionCandidates(); - - // get all jenkins job - List jobs = Jenkins.getInstance().getAllItems(Job.class); - HashSet jobSet = new HashSet<>(); - for (int i = 0; i < jobs.size(); i++) { - String jobName = jobs.get(i).getName(); - - if (jobName.toLowerCase().startsWith(value.toLowerCase())) { - jobSet.add(jobName); - } - } - - for (String s : jobSet) { - auto.add(s); - } - - return auto; - } - - /** - * This method is called to populate the credentials list on the Jenkins config page. - */ - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, - @QueryParameter("target") final String target) { - StandardListBoxModel result = new StandardListBoxModel(); - result.includeEmptyValue(); - result.withMatching(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), - CredentialsProvider.lookupCredentials( - StandardUsernameCredentials.class, - context, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(target).build() - ) - ); - return result; - } - - /** - * This method is called to populate the policy list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillPolicyNameItems(@AncestorInPath ItemGroup context, - @RelativePath("..") @QueryParameter final String orgName, - @RelativePath("..") @QueryParameter final String toolchainName, - @RelativePath("..") @QueryParameter final String credentialsId) { - String targetAPI = chooseTargetAPI(environment); - try { - // if user changes to a different credential, need to get a new token - if (!credentialsId.equals(preCredentials) || Util.isNullOrEmpty(bluemixToken)) { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - preCredentials = credentialsId; - } - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######UPLOAD TEST RESULTS : calling getPolicyList#######"); - } - return getPolicyList(bluemixToken, orgName, toolchainName, environment, debug_mode); - } - - /** - * This method is called to populate the toolchain list on the Jenkins config page. - * @param context - * @param orgName - * @param credentialsId - * @return - */ - public ListBoxModel doFillToolchainNameItems(@AncestorInPath ItemGroup context, - @QueryParameter("credentialsId") final String credentialsId, - @QueryParameter("orgName") final String orgName) { - String targetAPI = chooseTargetAPI(environment); - try { - bluemixToken = getBluemixToken(context, credentialsId, targetAPI); - } catch (Exception e) { - return new ListBoxModel(); - } - if(debug_mode){ - LOGGER.info("#######UPLOAD TEST RESULTS : calling getToolchainList#######"); - } - ListBoxModel toolChainListBox = getToolchainList(bluemixToken, orgName, environment, debug_mode); - return toolChainListBox; - - } - - /** - * Required Method - * This is used to determine if this build step is applicable for your chosen project type. (FreeStyle, MultiConfiguration, Maven) - * Some plugin build steps might be made to be only available to MultiConfiguration projects. - * - * @param aClass The current project - * @return a boolean indicating whether this build step can be chose given the project type - */ - public boolean isApplicable(Class aClass) { - // Indicates that this builder can be used with all kinds of project types - // return FreeStyleProject.class.isAssignableFrom(aClass); - return true; - } - - public ListBoxModel doFillLifecycleStageItems(@QueryParameter("lifecycleStage") final String selection) { - return fillTestType(); - } - - public ListBoxModel doFillAdditionalLifecycleStageItems(@QueryParameter("additionalLifecycleStage") final String selection) { - return fillTestType(); - } - - /** - * fill the dropdown list of rule type - * @return the dropdown list model - */ - public ListBoxModel fillTestType() { - ListBoxModel model = new ListBoxModel(); - - model.add("Unit Test", "unittest"); - model.add("Functional Verification Test", "fvt"); - model.add("Code Coverage", "code"); - return model; - } - - /** - * Required Method - * @return The text to be displayed when selecting your build in the project - */ - public String getDisplayName() { - return "Publish test result to IBM Cloud DevOps"; - } - - @Override - public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { - // To persist global configuration information, - // set that to properties and call save(). - environment = formData.getString("environment"); - debug_mode = Boolean.parseBoolean(formData.getString("debug_mode")); - save(); - return super.configure(req,formData); - } - - public String getEnvironment() { - return environment; - } - public boolean getDebugMode() { - return debug_mode; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/TestResultModel.java b/src/main/java/com/ibm/devops/dra/TestResultModel.java deleted file mode 100644 index 2116651..0000000 --- a/src/main/java/com/ibm/devops/dra/TestResultModel.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - -/** - * Object for creating dummy test result file following mocha format - */ -public class TestResultModel{ - - // sub-model for stats - public static class Stats { - private Integer suites; - private Integer tests; - private Integer passes; - private Integer pending; - private Integer failures; - private String start; - private String end; - private Long duration; - - public Stats(Integer suites, - Integer tests, - Integer passes, - Integer pending, - Integer failures, - String start, - String end, - Long duration) { - this.suites = suites; - this.tests = tests; - this.passes = passes; - this.pending = pending; - this.failures = failures; - this.start = start; - this.end = end; - this.duration = duration; - } - - public Integer getSuites() { - return suites; - } - - public Integer getTests() { - return tests; - } - - public Integer getPasses() { - return passes; - } - - public Integer getPending() { - return pending; - } - - public Integer getFailures() { - return failures; - } - - public String getStart() { - return start; - } - - public String getEnd() { - return end; - } - - public Long getDuration() { - return duration; - } - } - - // sub-model for test - public static class Test { - private String title; - private String fullTitle; - private Long duration; - private Integer currentRetry; - private Object err; - - public Test(String title, - String fullTitle, - Long duration, - Integer currentRetry, - Object err) { - this.title = title; - this.fullTitle = fullTitle; - this.duration = duration; - this.currentRetry = currentRetry; - this.err = err; - } - - public String getTitle() { - return title; - } - - public String getFullTitle() { - return fullTitle; - } - - public Long getDuration() { - return duration; - } - - public Integer getCurrentRetry() { - return currentRetry; - } - - public Object getErr() { - return err; - } - } - - private Stats stats; - private Test[] tests; - private String[] pending; - private String[] failures; - private String[] passes; - - public TestResultModel(Stats stats, - Test[] tests, - String[] pending, - String[] failures, - String[] passes) { - this.stats = stats; - this.tests = tests.clone(); - this.pending = pending.clone(); - this.failures = failures.clone(); - this.passes = passes.clone(); - } - - public Stats getStats() { - return stats; - } - - public Test[] getTests() { - return tests.clone(); - } - - public String[] getPending() { - return pending.clone(); - } - - public String[] getFailures() { - return failures.clone(); - } - - public String[] getPasses() { - return passes.clone(); - } -} diff --git a/src/main/java/com/ibm/devops/dra/Util.java b/src/main/java/com/ibm/devops/dra/Util.java deleted file mode 100644 index 42d9143..0000000 --- a/src/main/java/com/ibm/devops/dra/Util.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra; - - -import hudson.EnvVars; -import java.io.PrintStream; - -/** - * Utilities functions - */ - -public class Util { - /** - * check if the str is null or empty - * @param str - * @return true if it is null or empty - */ - public static boolean isNullOrEmpty(String str) { - if (str == null || str.isEmpty()) { - return true; - } - return false; - } - - public static boolean allNotNullOrEmpty(String... strs) { - for (String str : strs) { - if (isNullOrEmpty(str)) { - return false; - } - } - return true; - } - - public static boolean validateEnvVariables(EnvVars envVars, PrintStream printStream) { - Boolean valid = true; - if(envVars != null) { - String org = getOrg(envVars); - String space = getSpace(envVars); - String appName = getAppName(envVars); - String user = getUser(envVars); - String pwd = getPassword(envVars); - String webhook = getWebhookUrl(envVars); - - // perform validation and warn for each missing required property - if (isNullOrEmpty(org)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_ORG"); - valid = false; - } - if (isNullOrEmpty(space)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_SPACE"); - valid = false; - } - if (isNullOrEmpty(appName)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_APP_NAME"); - valid = false; - } - if (isNullOrEmpty(user)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_CREDS_USR"); - valid = false; - } - if (isNullOrEmpty(pwd)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_CREDS_PSW"); - valid = false; - } - if (isNullOrEmpty(webhook)) { - printStream.println("[IBM Cloud DevOps] Missing required property IBM_CLOUD_DEVOPS_WEBHOOK_URL"); - valid = false; - } - } - return valid; - } - - public static String getWebhookUrl(EnvVars envVars) { - String webhook = envVars.get("IBM_CLOUD_DEVOPS_WEBHOOK_URL"); - //backward compatibility - if (isNullOrEmpty(webhook)) { - webhook = envVars.get("ICD_WEBHOOK_URL"); - } - return webhook; - } - - public static String getOrg(EnvVars envVars) { - String org = envVars.get("IBM_CLOUD_DEVOPS_ORG"); - //backward compatibility - if (isNullOrEmpty(org)) { - org = envVars.get("CF_ORG"); - } - return org; - } - - public static String getSpace(EnvVars envVars) { - String space = envVars.get("IBM_CLOUD_DEVOPS_SPACE"); - //backward compatibility - if (isNullOrEmpty(space)) { - space = envVars.get("CF_SPACE"); - } - return space; - } - - public static String getAppName(EnvVars envVars) { - String appName = envVars.get("IBM_CLOUD_DEVOPS_APP_NAME"); - //backward compatibility - if (isNullOrEmpty(appName)) { - appName = envVars.get("CF_APP"); - } - return appName; - } - - public static String getUser(EnvVars envVars) { - String user = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - //backward compatibility - if (isNullOrEmpty(user)) { - user = envVars.get("CF_CREDS_USR"); - } - return user; - } - - public static String getPassword(EnvVars envVars) { - String pwd = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - //backward compatibility - if (isNullOrEmpty(pwd)) { - pwd = envVars.get("CF_CREDS_PSW"); - } - return pwd; - } - - public static String getGitRepoUrl(EnvVars envVars) { - String gitUrl = envVars.get("GIT_URL"); - if (isNullOrEmpty(gitUrl)) { - gitUrl = envVars.get("GIT_REPO"); // used in pipeline scripts - } - return gitUrl; - } - - public static String getGitBranch(EnvVars envVars) { - return envVars.get("GIT_BRANCH"); - } - - public static String getGitCommit(EnvVars envVars) { - return envVars.get("GIT_COMMIT"); - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStep.java b/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStep.java deleted file mode 100644 index 2c471c3..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStep.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import hudson.Extension; -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class EvaluateGateStep extends AbstractStepImpl { - // optional form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainId; - - // required parameters to support pipeline script - private String policy; - - // optional gate parameters - private String forceDecision; - private String environment; - private String buildNumber; - - @DataBoundConstructor - public EvaluateGateStep(String policy) { - this.policy = policy; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainId(String toolchainId) { - this.toolchainId = toolchainId; - } - - @DataBoundSetter - public void setEnvironment(String environment) { - this.environment = environment; - } - - @DataBoundSetter - public void setForceDecision(String forceDecision) { - this.forceDecision = forceDecision; - } - - @DataBoundSetter - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getToolchainId() { - return toolchainId; - } - - public String getEnvironment() { - return environment; - } - - public String getPolicy() { - return policy; - } - - public String getForceDecision() { - return forceDecision; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - - public DescriptorImpl() { super(EvaluateGateStepExecution.class); } - - @Override - public String getFunctionName() { - return "evaluateGate"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "IBM Cloud DevOps Gate"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStepExecution.java b/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStepExecution.java deleted file mode 100644 index 228fc5e..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/EvaluateGateStepExecution.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import com.ibm.devops.dra.EvaluateGate; -import com.ibm.devops.dra.Util; -import hudson.AbortException; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.Run; -import hudson.model.TaskListener; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; - -import javax.inject.Inject; -import java.io.PrintStream; - -public class EvaluateGateStepExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient EvaluateGateStep step; - - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient FilePath ws; - @StepContextParameter - private transient Launcher launcher; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - - PrintStream printStream = listener.getLogger(); - - String orgName = Util.isNullOrEmpty(step.getOrgName()) ? envVars.get("IBM_CLOUD_DEVOPS_ORG") : step.getOrgName(); - String applicationName = Util.isNullOrEmpty(step.getApplicationName()) ? envVars.get("IBM_CLOUD_DEVOPS_APP_NAME") : step.getApplicationName(); - String toolchainName = Util.isNullOrEmpty(step.getToolchainId()) ? envVars.get("IBM_CLOUD_DEVOPS_TOOLCHAIN_ID") : step.getToolchainId(); - String username = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - String password = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - - //check all the required env vars - if (!Util.allNotNullOrEmpty(orgName, applicationName,toolchainName, username, password)) { - printStream.println("[IBM Cloud DevOps] Missing environment variables configurations, please specify all required environment variables in the pipeline"); - printStream.println("[IBM Cloud DevOps] Error: Failed to get Gate decision."); - return null; - } - - String policy = step.getPolicy(); - if (Util.isNullOrEmpty(policy)) { - printStream.println("[IBM Cloud DevOps] evaluateGate is missing required parameters, " + - "please make sure you specify \"policy\""); - printStream.println("[IBM Cloud DevOps] Error: Failed to run evaluate Gate."); - return null; - } - - Boolean willDisrupt = false; - if (!Util.isNullOrEmpty(step.getForceDecision()) && step.getForceDecision().toLowerCase().equals("true")) { - willDisrupt = true; - } - - // optional build number, if user wants to set their own build number - String buildNumber = step.getBuildNumber(); - EvaluateGate evaluateGate = new EvaluateGate( - policy, - orgName, - applicationName, - toolchainName, - step.getEnvironment(), - username, - password, - willDisrupt); - try { - if (!Util.isNullOrEmpty(buildNumber)) { - evaluateGate.setBuildNumber(buildNumber); - } - evaluateGate.perform(build, ws, launcher, listener); - } catch (AbortException e) { - throw new AbortException("Decision is fail"); - } - - return null; - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishBuildStep.java b/src/main/java/com/ibm/devops/dra/steps/PublishBuildStep.java deleted file mode 100644 index 4d641de..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishBuildStep.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import hudson.Extension; -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class PublishBuildStep extends AbstractStepImpl { - // optional form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainId; - - // required parameters to support pipeline script - private String result; - private String gitRepo; - private String gitBranch; - private String gitCommit; - - // custom build number, optional - private String buildNumber; - - @DataBoundConstructor - public PublishBuildStep(String result, String gitRepo, String gitBranch, String gitCommit) { - this.gitRepo = gitRepo; - this.gitBranch = gitBranch; - this.gitCommit = gitCommit; - this.result = result; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainId(String toolchainId) { - this.toolchainId = toolchainId; - } - - @DataBoundSetter - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getGitRepo() { - return gitRepo; - } - - public String getGitBranch() { - return gitBranch; - } - - public String getGitCommit() { - return gitCommit; - } - - public String getToolchainId() { - return toolchainId; - } - - public String getResult() { - return result; - } - - public String getBuildNumber() { - return buildNumber; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - - public DescriptorImpl() { super(PublishBuildStepExecution.class); } - - @Override - public String getFunctionName() { - return "publishBuildRecord"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Publish build record to IBM Cloud DevOps"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishBuildStepExecution.java b/src/main/java/com/ibm/devops/dra/steps/PublishBuildStepExecution.java deleted file mode 100644 index 1f5b23d..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishBuildStepExecution.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import com.ibm.devops.dra.PublishBuild; -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.Run; -import hudson.model.TaskListener; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; - -import javax.inject.Inject; -import java.io.PrintStream; - -public class PublishBuildStepExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient PublishBuildStep step; - - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient FilePath ws; - @StepContextParameter - private transient Launcher launcher; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - - PrintStream printStream = listener.getLogger(); - - String orgName = Util.isNullOrEmpty(step.getOrgName()) ? envVars.get("IBM_CLOUD_DEVOPS_ORG") : step.getOrgName(); - String applicationName = Util.isNullOrEmpty(step.getApplicationName()) ? envVars.get("IBM_CLOUD_DEVOPS_APP_NAME") : step.getApplicationName(); - String toolchainName = Util.isNullOrEmpty(step.getToolchainId()) ? envVars.get("IBM_CLOUD_DEVOPS_TOOLCHAIN_ID") : step.getToolchainId(); - String username = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - String password = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - - //check all the required env vars - if (!Util.allNotNullOrEmpty(orgName, applicationName,toolchainName, username, password)) { - printStream.println("[IBM Cloud DevOps] Missing environment variables configurations, please specify all required environment variables in the pipeline"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Build Record."); - return null; - } - - //check all the required parameters - String result = step.getResult(); - String gitRepo = step.getGitRepo(); - String gitBranch = step.getGitBranch(); - String gitCommit = step.getGitCommit(); - // optional build number, if user wants to set their own build number - String buildNumber = step.getBuildNumber(); - - if (!Util.allNotNullOrEmpty(result, gitRepo, gitBranch, gitCommit)) { - printStream.println("[IBM Cloud DevOps] publishBuildRecord is missing required parameters, " + - "please make sure you specify \"result\", \"gitRepo\", \"gitBranch\", \"gitCommit\""); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Build Record."); - return null; - } - - if (result.equals("SUCCESS") || result.equals("FAIL")) { - PublishBuild publishBuild = new PublishBuild( - result, - gitRepo, - gitBranch, - gitCommit, - orgName, - applicationName, - toolchainName, - username, - password); - - if (!Util.isNullOrEmpty(buildNumber)) { - publishBuild.setBuildNumber(buildNumber); - } - publishBuild.perform(build, ws, launcher, listener); - } else { - printStream.println("[IBM Cloud DevOps] the \"result\" in the publishBuildRecord should be either \"SUCCESS\" or \"FAIL\""); - } - - return null; - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishDeployStep.java b/src/main/java/com/ibm/devops/dra/steps/PublishDeployStep.java deleted file mode 100644 index 073b4e3..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishDeployStep.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import hudson.Extension; -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class PublishDeployStep extends AbstractStepImpl { - // optional form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainId; - - // required parameters to support pipeline script - private String result; - private String environment; - private String appUrl; - - // custom build number, optional - private String buildNumber; - - @DataBoundConstructor - public PublishDeployStep(String result, String environment, String appUrl) { - this.environment = environment; - this.appUrl = appUrl; - this.result = result; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainId(String toolchainId) { - this.toolchainId = toolchainId; - } - - @DataBoundSetter - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getEnvironment() { - return environment; - } - - public String getAppUrl() { - return appUrl; - } - - public String getToolchainId() { - return toolchainId; - } - - public String getResult() { - return result; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - - public DescriptorImpl() { super(PublishDeployStepExecution.class); } - - @Override - public String getFunctionName() { - return "publishDeployRecord"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Publish deploy record to IBM Cloud DevOps"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishDeployStepExecution.java b/src/main/java/com/ibm/devops/dra/steps/PublishDeployStepExecution.java deleted file mode 100644 index dd33954..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishDeployStepExecution.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import com.ibm.devops.dra.PublishDeploy; -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.Run; -import hudson.model.TaskListener; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; - -import javax.inject.Inject; -import java.io.PrintStream; - -public class PublishDeployStepExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient PublishDeployStep step; - - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient FilePath ws; - @StepContextParameter - private transient Launcher launcher; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - - @Override - protected Void run() throws Exception { - - PrintStream printStream = listener.getLogger(); - - String orgName = Util.isNullOrEmpty(step.getOrgName()) ? envVars.get("IBM_CLOUD_DEVOPS_ORG") : step.getOrgName(); - String applicationName = Util.isNullOrEmpty(step.getApplicationName()) ? envVars.get("IBM_CLOUD_DEVOPS_APP_NAME") : step.getApplicationName(); - String toolchainName = Util.isNullOrEmpty(step.getToolchainId()) ? envVars.get("IBM_CLOUD_DEVOPS_TOOLCHAIN_ID") : step.getToolchainId(); - String username = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - String password = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - - //check all the required env vars - if (!Util.allNotNullOrEmpty(orgName, applicationName,toolchainName, username, password)) { - printStream.println("[IBM Cloud DevOps] Missing environment variables configurations, please specify all required environment variables in the pipeline"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Deploy Record."); - return null; - } - - //check all the required parameters - String environment = step.getEnvironment(); - String result = step.getResult(); - // optional build number, if user wants to set their own build number - String buildNumber = step.getBuildNumber(); - if (!Util.allNotNullOrEmpty(result, environment)) { - printStream.println("[IBM Cloud DevOps] publishDeployRecord is missing required parameters, " + - "please make sure you specify \"result\" and \"environment\""); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Deploy Record."); - return null; - } - - if (result.equals("SUCCESS") || result.equals("FAIL")) { - PublishDeploy publishDeploy = new PublishDeploy( - environment, - step.getAppUrl(), - result, - toolchainName, - applicationName, - orgName, - username, - password); - if (!Util.isNullOrEmpty(buildNumber)) { - publishDeploy.setBuildNumber(buildNumber); - } - publishDeploy.perform(build, ws, launcher, listener); - } else { - printStream.println("[IBM Cloud DevOps] the \"result\" in the publishDeployRecord should be either \"SUCCESS\" or \"FAIL\""); - } - return null; - } -} - diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishSQStep.java b/src/main/java/com/ibm/devops/dra/steps/PublishSQStep.java deleted file mode 100644 index a045682..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishSQStep.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import hudson.Extension; -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class PublishSQStep extends AbstractStepImpl { - // optional form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainId; - private String environment; - - // required parameters - private String SQHostURL; - private String SQAuthToken; - private String SQProjectKey; - - // custom build number, optional - private String buildNumber; - - @DataBoundConstructor - public PublishSQStep(String SQHostURL, String SQAuthToken, String SQProjectKey) { - - this.SQHostURL = SQHostURL; - this.SQAuthToken = SQAuthToken; - this.SQProjectKey = SQProjectKey; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainId(String toolchainId) { - this.toolchainId = toolchainId; - } - - @DataBoundSetter - public void setEnvironment(String environment) { - this.environment = environment; - } - - @DataBoundSetter - public void setSQHostURL(String SQHostURL) { - this.SQHostURL = SQHostURL; - } - - @DataBoundSetter - public void setSQAuthToken(String SQAuthToken) { - this.SQAuthToken = SQAuthToken; - } - - @DataBoundSetter - public void setSQProjectKey(String SQProjectKey) { - this.SQProjectKey = SQProjectKey; - } - - @DataBoundSetter - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getToolchainId() { - return toolchainId; - } - - public String getEnvironment() { - return environment; - } - - public String getSQHostURL() { - return SQHostURL; - } - - public String getSQAuthToken() { - return SQAuthToken; - } - - public String getSQProjectKey() { - return SQProjectKey; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - - public DescriptorImpl() { super(PublishSQStepExecution.class); } - - @Override - public String getFunctionName() { - return "publishSQResults"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Publish SonarQube test results to IBM Cloud DevOps"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishSQStepExecution.java b/src/main/java/com/ibm/devops/dra/steps/PublishSQStepExecution.java deleted file mode 100644 index 62dfd30..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishSQStepExecution.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import com.ibm.devops.dra.PublishSQ; -import com.ibm.devops.dra.steps.PublishSQStep; -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.Run; -import hudson.model.TaskListener; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; - -import javax.inject.Inject; -import java.io.PrintStream; - -public class PublishSQStepExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient PublishSQStep step; - - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient FilePath ws; - @StepContextParameter - private transient Launcher launcher; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - - PrintStream printStream = listener.getLogger(); - - String orgName = Util.isNullOrEmpty(step.getOrgName()) ? envVars.get("IBM_CLOUD_DEVOPS_ORG") : step.getOrgName(); - String applicationName = Util.isNullOrEmpty(step.getApplicationName()) ? envVars.get("IBM_CLOUD_DEVOPS_APP_NAME") : step.getApplicationName(); - String toolchainName = Util.isNullOrEmpty(step.getToolchainId()) ? envVars.get("IBM_CLOUD_DEVOPS_TOOLCHAIN_ID") : step.getToolchainId(); - String IBMusername = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - String IBMpassword = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - // Project Key defaults to app name if nothing is passed in - String SQProjectKey = step.getSQProjectKey(); - String SQHostURL = step.getSQHostURL(); - String SQAuthToken = step.getSQAuthToken(); - - // optional build number, if user wants to set their own build number - String buildNumber = step.getBuildNumber(); - - //check all the required env vars - if (!Util.allNotNullOrEmpty(orgName, applicationName, toolchainName, IBMusername, IBMpassword, SQAuthToken, SQProjectKey, SQHostURL)) { - printStream.println("[IBM Cloud DevOps] Missing environment variables configurations, please specify all required environment variables in the pipeline"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Test Result."); - return null; - } - - PublishSQ publisher = new PublishSQ( - orgName, - applicationName, - toolchainName, - SQProjectKey, - SQHostURL, - SQAuthToken, - IBMusername, - IBMpassword); - - if (!Util.isNullOrEmpty(buildNumber)) { - publisher.setBuildNumber(buildNumber); - } - publisher.perform(build, ws, launcher, listener); - - return null; - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishTestStep.java b/src/main/java/com/ibm/devops/dra/steps/PublishTestStep.java deleted file mode 100644 index 9284bce..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishTestStep.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import hudson.Extension; -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class PublishTestStep extends AbstractStepImpl { - // optional form fields from UI - private String applicationName; - private String orgName; - private String credentialsId; - private String toolchainId; - private String environment; - - // required parameters - private String type; - private String fileLocation; - // custom build number, optional - private String buildNumber; - - @DataBoundConstructor - public PublishTestStep(String type, String fileLocation) { - this.type = type; - this.fileLocation = fileLocation; - } - - @DataBoundSetter - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @DataBoundSetter - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - @DataBoundSetter - public void setCredentialsId(String credentialsId) { - this.credentialsId = credentialsId; - } - - @DataBoundSetter - public void setToolchainId(String toolchainId) { - this.toolchainId = toolchainId; - } - - @DataBoundSetter - public void setEnvironment(String environment) { - this.environment = environment; - } - - @DataBoundSetter - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - public String getBuildNumber() { - return buildNumber; - } - - public String getApplicationName() { - return applicationName; - } - - public String getOrgName() { - return orgName; - } - - public String getCredentialsId() { - return credentialsId; - } - - public String getToolchainId() { - return toolchainId; - } - - public String getEnvironment() { - return environment; - } - - public String getType() { - return type; - } - - public String getFileLocation() { - return fileLocation; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - - public DescriptorImpl() { super(PublishTestStepExecution.class); } - - @Override - public String getFunctionName() { - return "publishTestResult"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Publish test result to IBM Cloud DevOps"; - } - } -} diff --git a/src/main/java/com/ibm/devops/dra/steps/PublishTestStepExecution.java b/src/main/java/com/ibm/devops/dra/steps/PublishTestStepExecution.java deleted file mode 100644 index 5e6d877..0000000 --- a/src/main/java/com/ibm/devops/dra/steps/PublishTestStepExecution.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.dra.steps; - -import com.ibm.devops.dra.PublishTest; -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.model.Run; -import hudson.model.TaskListener; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; - -import javax.inject.Inject; -import java.io.PrintStream; - -public class PublishTestStepExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient PublishTestStep step; - - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient FilePath ws; - @StepContextParameter - private transient Launcher launcher; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - - PrintStream printStream = listener.getLogger(); - - String orgName = Util.isNullOrEmpty(step.getOrgName()) ? envVars.get("IBM_CLOUD_DEVOPS_ORG") : step.getOrgName(); - String applicationName = Util.isNullOrEmpty(step.getApplicationName()) ? envVars.get("IBM_CLOUD_DEVOPS_APP_NAME") : step.getApplicationName(); - String toolchainName = Util.isNullOrEmpty(step.getToolchainId()) ? envVars.get("IBM_CLOUD_DEVOPS_TOOLCHAIN_ID") : step.getToolchainId(); - String username = envVars.get("IBM_CLOUD_DEVOPS_CREDS_USR"); - String password = envVars.get("IBM_CLOUD_DEVOPS_CREDS_PSW"); - - //check all the required env vars - if (!Util.allNotNullOrEmpty(orgName, applicationName,toolchainName, username, password)) { - printStream.println("[IBM Cloud DevOps] Missing environment variables configurations, please specify all required environment variables in the pipeline"); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Test Result."); - return null; - } - - //check all the required parameters - String type = step.getType(); - String fileLocation = step.getFileLocation(); - // optional build number, if user wants to set their own build number - String buildNumber = step.getBuildNumber(); - - if (!Util.allNotNullOrEmpty(type, fileLocation)) { - printStream.println("[IBM Cloud DevOps] publishTestResult is missing required parameters, " + - "please make sure you specify \"type\", \"fileLocation\""); - printStream.println("[IBM Cloud DevOps] Error: Failed to upload Test Result."); - return null; - } - - if (type.equals("unittest") || type.equals("code") || type.equals("fvt")) { - PublishTest publishTest = new PublishTest( - type, - fileLocation, - step.getEnvironment(), - orgName, - applicationName, - toolchainName, - username, - password); - if (!Util.isNullOrEmpty(buildNumber)) { - publishTest.setBuildNumber(buildNumber); - } - publishTest.perform(build, ws, launcher, listener); - } else { - printStream.println("[IBM Cloud DevOps] the \"type\" in the publishTestResult should be either \"unittest\", \"code\" or \"fvt\""); - } - - return null; - } -} diff --git a/src/main/java/com/ibm/devops/notification/BuildListener.java b/src/main/java/com/ibm/devops/notification/BuildListener.java deleted file mode 100644 index 089836e..0000000 --- a/src/main/java/com/ibm/devops/notification/BuildListener.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - - - Copyright 2016, 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.Extension; -import hudson.model.*; -import hudson.model.listeners.RunListener; -import net.sf.json.JSONObject; -import java.io.PrintStream; - -@Extension -public class BuildListener extends RunListener { - - public BuildListener(){ - super(AbstractBuild.class); - } - - @Override - public void onStarted(AbstractBuild r, TaskListener listener) { - handleEvent(r, listener, "STARTED"); - } - - @Override - public void onCompleted(AbstractBuild r, TaskListener listener) { - handleEvent(r, listener, "COMPLETED"); - } - - @Override - public void onFinalized(AbstractBuild r){ - handleEvent(r, TaskListener.NULL, "FINALIZED"); - } - - private void handleEvent(AbstractBuild r, TaskListener listener, String phase) { - OTCNotifier notifier = EventHandler.findPublisher(r); - PrintStream printStream = listener.getLogger(); - EnvVars envVars = EventHandler.getEnv(r, listener, printStream); - String webhook = Util.getWebhookUrl(envVars); - Result result = r.getResult(); - - // OTC Notifier - if(EventHandler.isRelevant(notifier, phase, result)) { - String resultString = null; - if(result != null){ - resultString = result.toString(); - } - - JSONObject message = MessageHandler.buildMessage(r, envVars, phase, resultString); - MessageHandler.postToWebhook(webhook, false, message, printStream); - } - - // deployable mapping - if(EventHandler.shouldPostDeployableMappingMessage(notifier, phase, result)) { - printStream.println("[IBM Cloud DevOps] Building Deployable Message."); - String resultString = null; - if(result != null){ - resultString = result.toString(); - } - - if (Util.validateEnvVariables(envVars, printStream)) { - JSONObject message = MessageHandler.buildDeployableMappingMessage(envVars, printStream); - printStream.println("[IBM Cloud DevOps] Sending Deployable Message."); - MessageHandler.postToWebhook(webhook, true, message, printStream); - } else { - printStream.println("[IBM Cloud DevOps] Not sending Deployable Message due to missing required property."); - } - } else { - printStream.println("[IBM Cloud DevOps] Not building Deployable Message."); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/ibm/devops/notification/EventHandler.java b/src/main/java/com/ibm/devops/notification/EventHandler.java deleted file mode 100644 index aba80ac..0000000 --- a/src/main/java/com/ibm/devops/notification/EventHandler.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.model.AbstractBuild; -import hudson.model.Result; -import hudson.model.TaskListener; -import hudson.tasks.Publisher; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; - -public final class EventHandler { - /* - find OTCNotifer in the publisher list - */ - public static OTCNotifier findPublisher(AbstractBuild r){ - List publisherList = r.getProject().getPublishersList().toList(); - - //ensure that there is an OTCNotifier in the project - for(Publisher publisher: publisherList){ - if(publisher instanceof OTCNotifier){ - return (OTCNotifier) publisher; - } - } - - return null; - } - - /* - return the build env variables - */ - public static EnvVars getEnv(AbstractBuild r, TaskListener listener, PrintStream printStream){ - try { - return r.getEnvironment(listener); - } catch (IOException e) { - printStream.println("[IBM Cloud DevOps] Exception: "); - printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); - e.printStackTrace(printStream); - } catch (InterruptedException e) { - printStream.println("[IBM Cloud DevOps] Exception: "); - printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); - e.printStackTrace(printStream); - } - - return null; - } - - /* - Check job config to see if message should be sent. - */ - public static boolean isRelevant(OTCNotifier notifier, String phase, Result result){ - boolean onStarted; - boolean onCompleted; - boolean onFinalized; - boolean failureOnly; - - //Make sure OTC Notifier was found in the publisherList - if(notifier != null){ - onStarted = notifier.getOnStarted(); - onCompleted = notifier.getOnCompleted(); - onFinalized = notifier.getOnFinalized(); - failureOnly = notifier.getFailureOnly(); - - if(onStarted && "STARTED".equals(phase) || onCompleted && "COMPLETED".equals(phase) - || onFinalized && "FINALIZED".equals(phase)){//check selections - if(failureOnly && result != null && result.equals(Result.FAILURE) || !failureOnly){//check failureOnly - return true; - } - } - } - - return false; - } - - /* - Returns whether deployable mapping message should be sent. - */ - public static boolean shouldPostDeployableMappingMessage(OTCNotifier notifier, String phase, Result result){ - // publish deployable mapping message only is traceability is enabled, phase is completed and build is successful - if(notifier != null && notifier.getEnableTraceability()){ - if ("COMPLETED".equals(phase) && result.equals(Result.SUCCESS)){ - return true; - } - } - return false; - } -} diff --git a/src/main/java/com/ibm/devops/notification/MessageHandler.java b/src/main/java/com/ibm/devops/notification/MessageHandler.java deleted file mode 100644 index 95fd130..0000000 --- a/src/main/java/com/ibm/devops/notification/MessageHandler.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.AbstractDevOpsAction; -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.model.Run; -import hudson.model.Job; -import jenkins.model.Jenkins; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.HttpClients; -import java.io.IOException; -import java.io.PrintStream; - -//build message that will be posted to the webhook -public final class MessageHandler { - public static JSONObject buildMessage(Run r, EnvVars envVars, String phase, String result){ - JSONObject message = new JSONObject(); - JSONObject build = new JSONObject(); - JSONObject scm = new JSONObject(); - - Job job = r.getParent(); - String rootUrl = Jenkins.getInstance().getRootUrl(); - - //setup scm - if(envVars != null) { - String gitCommit = envVars.get("GIT_COMMIT"); - String gitBranch = envVars.get("GIT_BRANCH"); - String gitPreviousCommit = envVars.get("GIT_PREVIOUS_COMMIT"); - String gitPreviousSuccessfulCommit = envVars.get("GIT_PREVIOUS_SUCCESSFUL_COMMIT"); - String gitUrl = envVars.get("GIT_URL"); - String gitCommitterName = envVars.get("GIT_COMMITTER_NAME"); - String gitCommitterEmail = envVars.get("GIT_COMMITTER_EMAIL"); - String gitAuthorName = envVars.get("GIT_AUTHOR_NAME"); - String gitAuthorEmail = envVars.get("GIT_AUTHOR_EMAIL"); - - if (gitCommit != null) { - scm.put("git_commit", gitCommit); - } - - if (gitBranch != null) { - scm.put("git_branch", gitBranch); - } - - if (gitPreviousCommit != null) { - scm.put("git_previous_commit", gitPreviousCommit); - } - - if (gitPreviousSuccessfulCommit != null) { - scm.put("git_previous_successful_commit", gitPreviousSuccessfulCommit); - } - - if (gitUrl != null) { - scm.put("git_url", gitUrl); - } - - if (gitCommitterName != null) { - scm.put("git_committer_name", gitCommitterName); - } - - if (gitCommitterEmail != null) { - scm.put("git_committer_email", gitCommitterEmail); - } - - if (gitAuthorName != null) { - scm.put("git_author_name", gitAuthorName); - } - - if (gitAuthorEmail != null) { - scm.put("git_author_email", gitAuthorEmail); - } - } - - //setup the build object - build.put("number", r.getNumber()); - build.put("queue_id", r.getQueueId()); - build.put("phase", phase); - build.put("url", r.getUrl()); - - if(rootUrl != null){ - build.put("full_url", rootUrl + r.getUrl()); - } else{ - build.put("full_url", ""); - } - - if(result != null){ - build.put("status", result); - } - - if(!"STARTED".equals(phase)) { - build.put("duration", r.getDuration()); - } - - build.put("scm", scm); - - //setup the message - message.put("name", job.getName()); - message.put("url", job.getUrl()); - message.put("build", build); - - return message; - } - - //post message to webhook - public static void postToWebhook(String webhook, boolean deployableMessage, JSONObject message, PrintStream printStream){ - //check webhook - if(Util.isNullOrEmpty(webhook)){ - printStream.println("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set."); - printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); - } else { - // set a 5 seconds timeout - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setSocketTimeout(5000) - .setConnectTimeout(5000) - .setConnectionRequestTimeout(5000) - .build(); - CloseableHttpClient httpClient = HttpClients.custom() - .setDefaultRequestConfig(defaultRequestConfig) - .build(); - HttpPost postMethod = new HttpPost(webhook); - try { - StringEntity data = new StringEntity(message.toString()); - postMethod.setEntity(data); - postMethod = Proxy.addProxyInformation(postMethod); - postMethod.addHeader("Content-Type", "application/json"); - - if (deployableMessage) { - postMethod.addHeader("x-create-connection", "true"); - printStream.println("[IBM Cloud DevOps] Sending Deployable Mapping message to webhook:"); - printStream.println(message); - } - - CloseableHttpResponse response = httpClient.execute(postMethod); - - if (response.getStatusLine().toString().matches(".*2([0-9]{2}).*")) { - printStream.println("[IBM Cloud DevOps] Message successfully posted to webhook."); - } else { - printStream.println("[IBM Cloud DevOps] Message failed, response status: " + response.getStatusLine()); - } - } catch (IOException e) { - printStream.println("[IBM Cloud DevOps] IOException, could not post to webhook:"); - e.printStackTrace(printStream); - } - } - } - - public static JSONObject buildDeployableMappingMessage(EnvVars envVars, PrintStream printStream){ - String environment = null; - // for debugging purpose only, uncomment the line below - // environment = "dev"; // to target YS1 - try { - JSONObject deployableMappingMessage; - // API - String apiUrl= AbstractDevOpsAction.chooseTargetAPI(environment); - - // get bluemix token first - String userId= Util.getUser(envVars); - String pwd= Util.getPassword(envVars); - - String bluemixToken = AbstractDevOpsAction.getBluemixToken(userId, pwd, apiUrl); - - // org details - JSONObject org = new JSONObject(); - String orgName = Util.getOrg(envVars); - org.put("Name" , orgName); - String orgId= AbstractDevOpsAction.getOrgId(bluemixToken, orgName, environment, false); - org.put("Guid" , orgId); - - // space details - JSONObject space = new JSONObject(); - String spaceName = Util.getSpace(envVars); - space.put("Name" , spaceName); - String spaceId= AbstractDevOpsAction.getSpaceId(bluemixToken, spaceName, environment, false); - space.put("Guid" , spaceId); - - // app details - JSONObject app = new JSONObject(); - String appName = Util.getAppName(envVars); - app.put("Name" , appName); - String appId= AbstractDevOpsAction.getAppId(bluemixToken, appName, orgName, spaceName, environment, false); - app.put("Guid" , appId); - - // Git - JSONArray gitData= MessageUtil.buildGitData(envVars, printStream); - - // format deployable message - deployableMappingMessage = MessageUtil.formatDeployableMappingMessage(org, space, app, apiUrl, gitData, printStream); - - return deployableMappingMessage; - - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Unexpected Exception encountered while building deployable message:"); - e.printStackTrace(printStream); - } - - return new JSONObject(); - } -} diff --git a/src/main/java/com/ibm/devops/notification/MessageUtil.java b/src/main/java/com/ibm/devops/notification/MessageUtil.java deleted file mode 100644 index 8bccbcd..0000000 --- a/src/main/java/com/ibm/devops/notification/MessageUtil.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import java.io.PrintStream; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; - -/** - * Message Utilities functions - */ - -public class MessageUtil { - - public static JSONArray buildGitData(EnvVars envVars, PrintStream printStream) { - try { - String gitUrl = Util.getGitRepoUrl(envVars); - String gitBranch = Util.getGitBranch(envVars); - String gitCommit = Util.getGitCommit(envVars); - - JSONObject gitInfo = new JSONObject(); - gitInfo.put("GitURL" , gitUrl); - gitInfo.put("GitBranch" , gitBranch); - gitInfo.put("GitCommitID" , gitCommit); - - JSONArray gitData = new JSONArray(); - gitData.add(gitInfo); - - return gitData; - - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Error: Failed to build Git data."); - e.printStackTrace(printStream); - throw e; - } - } - - public static JSONObject formatDeployableMappingMessage(JSONObject org, JSONObject space, JSONObject app, String apiUrl, JSONArray gitData, PrintStream printStream) { - try { - JSONObject deployableMappingMessage = new JSONObject(); - deployableMappingMessage.put("Org" , org); - deployableMappingMessage.put("Space" , space); - deployableMappingMessage.put("App" , app); - deployableMappingMessage.put("ApiEndpoint" , apiUrl); - deployableMappingMessage.put("Method" , "POST"); - deployableMappingMessage.put("GitData" , gitData); - return deployableMappingMessage; - - } catch (Exception e) { - printStream.println("[IBM Cloud DevOps] Error: Failed to build Deployable Mapping Message."); - e.printStackTrace(printStream); - throw e; - } - } -} diff --git a/src/main/java/com/ibm/devops/notification/OTCNotifier.java b/src/main/java/com/ibm/devops/notification/OTCNotifier.java deleted file mode 100644 index a75793e..0000000 --- a/src/main/java/com/ibm/devops/notification/OTCNotifier.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import hudson.Extension; -import hudson.Launcher; -import hudson.model.AbstractBuild; -import hudson.model.AbstractProject; -import hudson.model.BuildListener; -import hudson.tasks.BuildStepDescriptor; -import hudson.tasks.BuildStepMonitor; -import hudson.tasks.Notifier; -import hudson.tasks.Publisher; -import org.kohsuke.stapler.DataBoundConstructor; -import java.io.IOException; - -public class OTCNotifier extends Notifier { - private boolean onStarted; - private boolean onCompleted; - private boolean onFinalized; - private boolean failureOnly; - private boolean enableTraceability; - - /* - The paramater names in @DataBoundConstructor need to match the fields in config.jelly exactly - */ - @DataBoundConstructor - public OTCNotifier(boolean onStarted, - boolean onCompleted, - boolean onFinalized, - boolean failureOnly, - boolean enableTraceability - ){ - this.onStarted = onStarted; - this.onCompleted = onCompleted; - this.onFinalized = onFinalized; - this.failureOnly = failureOnly; - this.enableTraceability = enableTraceability; - } - - /* - These methods are called by jenkins to populate the per-job config fields - */ - public Boolean getOnStarted(){ - return this.onStarted; - } - - public Boolean getOnCompleted(){ - return this.onCompleted; - } - - public Boolean getOnFinalized(){ - return this.onFinalized; - } - - public Boolean getFailureOnly(){ - return this.failureOnly; - } - - public Boolean getEnableTraceability(){ - return this.enableTraceability; - } - - public BuildStepMonitor getRequiredMonitorService() { - return BuildStepMonitor.NONE; - } - - @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - return true; - } - - @Override - public DescriptorImpl getDescriptor() { - return (DescriptorImpl)super.getDescriptor(); - } - - /* - The descriptor allows global configs for your plugin, this class will be passed to every instance of the plugin. - */ - @Extension // This indicates to Jenkins that this is an implementation of an extension point. - public static final class DescriptorImpl extends BuildStepDescriptor { - @Override - public String getDisplayName() { - return "Notify OTC";//This is the plugin name in the config - } - - public boolean isApplicable(Class aClass) { - return true; //It is always ok for someone to add this as a build step - } - } -} \ No newline at end of file diff --git a/src/main/java/com/ibm/devops/notification/Proxy.java b/src/main/java/com/ibm/devops/notification/Proxy.java deleted file mode 100644 index 2e6180d..0000000 --- a/src/main/java/com/ibm/devops/notification/Proxy.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import jenkins.model.Jenkins; -import hudson.ProxyConfiguration; -import org.apache.http.HttpHost; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.config.RequestConfig; -import com.ibm.devops.dra.Util; - -public final class Proxy { - public static HttpPost addProxyInformation (HttpPost instance) { - /* Add proxy to request if proxy settings in Jenkins UI are set. */ - ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; - if(proxyConfig != null){ - if((!Util.isNullOrEmpty(proxyConfig.name)) && proxyConfig.port != 0) { - HttpHost proxy = new HttpHost(proxyConfig.name, proxyConfig.port, "http"); - RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - instance.setConfig(config); - } - } - return instance; - } -} diff --git a/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationExecution.java b/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationExecution.java deleted file mode 100644 index 0d38910..0000000 --- a/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationExecution.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification.steps; - -import com.ibm.devops.dra.Util; -import com.ibm.devops.notification.MessageHandler; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; -import javax.inject.Inject; -import hudson.EnvVars; -import hudson.model.Run; -import hudson.model.TaskListener; -import net.sf.json.JSONObject; - - -import java.io.PrintStream; - -public class DeployableMappingNotificationExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient DeployableMappingNotificationStep step; - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - PrintStream printStream = listener.getLogger(); - String webhookUrl; - - if(Util.isNullOrEmpty(step.getWebhookUrl())){ - webhookUrl = Util.getWebhookUrl(envVars); - } else { - webhookUrl = step.getWebhookUrl(); - } - - String status = step.getStatus().trim(); - //check all the required env vars - if (!Util.allNotNullOrEmpty(status)) { - printStream.println("[IBM Cloud DevOps] Required parameter null or empty."); - printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); - return null; - } - - if ("SUCCESS".equals(status)) { // send deployable mapping message on for successful builds - JSONObject message = MessageHandler.buildDeployableMappingMessage(envVars, printStream); - MessageHandler.postToWebhook(webhookUrl, true, message, printStream); - } - return null; - } -} diff --git a/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationStep.java b/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationStep.java deleted file mode 100644 index 2d479ab..0000000 --- a/src/main/java/com/ibm/devops/notification/steps/DeployableMappingNotificationStep.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification.steps; - -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import hudson.Extension; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class DeployableMappingNotificationStep extends AbstractStepImpl { - //required parameter to support pipeline script - private String status; - - //option parameters - private String webhookUrl; - - @DataBoundConstructor - public DeployableMappingNotificationStep(String status){ - this.status = status; - } - - @DataBoundSetter - public void setWebhookUrl(String webhookUrl){ - this.webhookUrl = webhookUrl; - } - - public String getWebhookUrl(){ - return this.webhookUrl; - } - - public String getStatus(){ - return this.status; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - public DescriptorImpl() { super(DeployableMappingNotificationExecution.class); } - - @Override - public String getFunctionName() { - return "sendDeployableMessage"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Send deployable mapping message to OTC"; - } - } -} diff --git a/src/main/java/com/ibm/devops/notification/steps/OTCNotificationExecution.java b/src/main/java/com/ibm/devops/notification/steps/OTCNotificationExecution.java deleted file mode 100644 index 185f627..0000000 --- a/src/main/java/com/ibm/devops/notification/steps/OTCNotificationExecution.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification.steps; - -import com.ibm.devops.dra.Util; -import com.ibm.devops.notification.MessageHandler; -import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; -import org.jenkinsci.plugins.workflow.steps.StepContextParameter; -import javax.inject.Inject; -import hudson.EnvVars; -import hudson.model.Run; -import hudson.model.TaskListener; -import net.sf.json.JSONObject; - - -import java.io.PrintStream; - -public class OTCNotificationExecution extends AbstractSynchronousNonBlockingStepExecution { - private static final long serialVersionUID = 1L; - @Inject - private transient OTCNotificationStep step; - @StepContextParameter - private transient TaskListener listener; - @StepContextParameter - private transient Run build; - @StepContextParameter - private transient EnvVars envVars; - - @Override - protected Void run() throws Exception { - String stageName = step.getStageName().trim(); - String status = step.getStatus().trim(); - PrintStream printStream = listener.getLogger(); - String webhookUrl; - - if(Util.isNullOrEmpty(step.getWebhookUrl())){ - webhookUrl = Util.getWebhookUrl(envVars); - } else { - webhookUrl = step.getWebhookUrl(); - } - - //check all the required env vars - if (!Util.allNotNullOrEmpty(stageName, status)) { - printStream.println("[IBM Cloud DevOps] Required parameter null or empty."); - printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); - return null; - } - - JSONObject message = MessageHandler.buildMessage(build, envVars, stageName, status); - MessageHandler.postToWebhook(webhookUrl, false, message, printStream); - - return null; - } -} diff --git a/src/main/java/com/ibm/devops/notification/steps/OTCNotificationStep.java b/src/main/java/com/ibm/devops/notification/steps/OTCNotificationStep.java deleted file mode 100644 index 34f9409..0000000 --- a/src/main/java/com/ibm/devops/notification/steps/OTCNotificationStep.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification.steps; - -import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; -import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; -import hudson.Extension; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -import javax.annotation.Nonnull; - -public class OTCNotificationStep extends AbstractStepImpl { - //required parameter to support pipeline script - private String status; - private String stageName; - - //option parameters - private String webhookUrl; - - @DataBoundConstructor - public OTCNotificationStep(String stageName, String status){ - this.stageName = stageName; - this.status = status; - } - - @DataBoundSetter - public void setWebhookUrl(String webhookUrl){ - this.webhookUrl = webhookUrl; - } - - public String getWebhookUrl(){ - return this.webhookUrl; - } - - public String getStatus(){ - return this.status; - } - - public String getStageName(){ - return this.stageName; - } - - @Extension - public static class DescriptorImpl extends AbstractStepDescriptorImpl { - public DescriptorImpl() { super(OTCNotificationExecution.class); } - - @Override - public String getFunctionName() { - return "notifyOTC"; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Send notification to OTC"; - } - } -} diff --git a/src/main/resources/com/ibm/devops/dra/BuildPublisherAction/summary.jelly b/src/main/resources/com/ibm/devops/dra/BuildPublisherAction/summary.jelly deleted file mode 100755 index e1afa0a..0000000 --- a/src/main/resources/com/ibm/devops/dra/BuildPublisherAction/summary.jelly +++ /dev/null @@ -1,26 +0,0 @@ - - - - - -

IBM Cloud DevOps

- -

- Please click here to view the build status of all application - -

- - - diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/config.jelly b/src/main/resources/com/ibm/devops/dra/EvaluateGate/config.jelly deleted file mode 100644 index 6b307a6..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/config.jelly +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - -
diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/global.jelly b/src/main/resources/com/ibm/devops/dra/EvaluateGate/global.jelly deleted file mode 100644 index 0829bf9..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/global.jelly +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-additionalBuildInfo.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-additionalBuildInfo.html deleted file mode 100644 index 1b141d8..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-additionalBuildInfo.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box if the deployed app is not built in Jenkins. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-applicationName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-applicationName.html deleted file mode 100644 index 123f11f..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-applicationName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type a name for the application that information is being uploaded for. Use this application name when you configure DevOps Insights gates. You can use an environment variable, such as $APP_NAME. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildJobName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildJobName.html deleted file mode 100644 index 4a4049b..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildJobName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Enter the name of the build job that triggers this test job. You can use an environment variable, such as $BUILD_JOB. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildNumber.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildNumber.html deleted file mode 100644 index 1f71cd5..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-buildNumber.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Specify the number for external builds. You can define this number as an environment variable. . -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-credentialsId.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-credentialsId.html deleted file mode 100644 index 941d6ed..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-credentialsId.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a Bluemix ID from the menu. If no Bluemix IDs are in the menu, click Add to add one. Click Test Connection to verify the selected credentials. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-envName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-envName.html deleted file mode 100644 index ffc39b0..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-envName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the environment that this job deploys to. If this environment is your staging environment, type "STAGING." If this environment is your production requirement, type "PRODUCTION." If you do not specify staging and production environments, DevOps Insights cannot completely analyze your project. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-orgName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-orgName.html deleted file mode 100644 index f8feb78..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-orgName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the Bluemix organization that you want to use. You can type the name here or use an environment variable, such as $ORG_NAME, that is defined elsewhere. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-policyName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-policyName.html deleted file mode 100644 index cc57ab5..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-policyName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select the policy that you want this gate to enforce. You can create more policies in DevOps Insights. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-toolchainName.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-toolchainName.html deleted file mode 100644 index 42b2702..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-toolchainName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a toolchain. If you have not created a toolchain yet, create one here. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-willDisrupt.html b/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-willDisrupt.html deleted file mode 100644 index cff206c..0000000 --- a/src/main/resources/com/ibm/devops/dra/EvaluateGate/help-willDisrupt.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box to cancel associated Jenkins builds when this gate fails. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/GatePublisherAction/summary.jelly b/src/main/resources/com/ibm/devops/dra/GatePublisherAction/summary.jelly deleted file mode 100755 index 9e7861b..0000000 --- a/src/main/resources/com/ibm/devops/dra/GatePublisherAction/summary.jelly +++ /dev/null @@ -1,30 +0,0 @@ - - - - - -

IBM Cloud DevOps

-

Policy Name: ${it.policyName}

-

Decision: ${it.decision}

-

- Click here to view the Gate Evaluation Report. -

-

- Click here to view the Deployment Risk Dashboard. -

- - - -
diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/config.jelly b/src/main/resources/com/ibm/devops/dra/PublishBuild/config.jelly deleted file mode 100644 index 73f92de..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/config.jelly +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/global.jelly b/src/main/resources/com/ibm/devops/dra/PublishBuild/global.jelly deleted file mode 100644 index 60f3d8c..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/global.jelly +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-additionalBuildInfo.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-additionalBuildInfo.html deleted file mode 100644 index 5662e10..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-additionalBuildInfo.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box if you want to set your own build number. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-applicationName.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-applicationName.html deleted file mode 100644 index 123f11f..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-applicationName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type a name for the application that information is being uploaded for. Use this application name when you configure DevOps Insights gates. You can use an environment variable, such as $APP_NAME. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-buildNumber.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-buildNumber.html deleted file mode 100644 index 6ca7fb8..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-buildNumber.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Specify the custom build number for this job. You can define this number as an environment variable. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-credentialsId.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-credentialsId.html deleted file mode 100644 index cd32d9a..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-credentialsId.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a Bluemix ID from the menu. If no Bluemix IDs are in the menu, click Add to add one. Click Test Connection to verify the selected credentials. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-orgName.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-orgName.html deleted file mode 100644 index f8feb78..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-orgName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the Bluemix organization that you want to use. You can type the name here or use an environment variable, such as $ORG_NAME, that is defined elsewhere. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-toolchainName.html b/src/main/resources/com/ibm/devops/dra/PublishBuild/help-toolchainName.html deleted file mode 100644 index 42b2702..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishBuild/help-toolchainName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a toolchain. If you have not created a toolchain yet, create one here. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/config.jelly b/src/main/resources/com/ibm/devops/dra/PublishDeploy/config.jelly deleted file mode 100644 index b2ebfc9..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/config.jelly +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/global.jelly b/src/main/resources/com/ibm/devops/dra/PublishDeploy/global.jelly deleted file mode 100644 index 34e6be0..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/global.jelly +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-additionalBuildInfo.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-additionalBuildInfo.html deleted file mode 100644 index 999c790..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-additionalBuildInfo.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box if you want to set your own build number -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationName.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationName.html deleted file mode 100644 index 123f11f..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type a name for the application that information is being uploaded for. Use this application name when you configure DevOps Insights gates. You can use an environment variable, such as $APP_NAME. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationUrl.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationUrl.html deleted file mode 100644 index 3c86d17..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-applicationUrl.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Optional: If this is a web application, enter its URL. You can use an environment variable, such as $APP_URL. -
diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildJobName.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildJobName.html deleted file mode 100644 index 243dd3b..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildJobName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Enter the name of the build job that triggers this test job. You can use an environment variable, such as $BUILD_JOB. -
diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildNumber.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildNumber.html deleted file mode 100644 index 6ca7fb8..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-buildNumber.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Specify the custom build number for this job. You can define this number as an environment variable. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-credentialsId.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-credentialsId.html deleted file mode 100644 index cd32d9a..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-credentialsId.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a Bluemix ID from the menu. If no Bluemix IDs are in the menu, click Add to add one. Click Test Connection to verify the selected credentials. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-environmentName.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-environmentName.html deleted file mode 100644 index 731ad3a..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-environmentName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the environment that this job deploys to. If this environment is your staging environment, type "STAGING." If this environment is your production requirement, type "PRODUCTION." If you do not specify staging and production environments, DevOps Insights cannot completely analyze your project. -
diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-orgName.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-orgName.html deleted file mode 100644 index f8feb78..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-orgName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the Bluemix organization that you want to use. You can type the name here or use an environment variable, such as $ORG_NAME, that is defined elsewhere. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-toolchainName.html b/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-toolchainName.html deleted file mode 100644 index 42b2702..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishDeploy/help-toolchainName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a toolchain. If you have not created a toolchain yet, create one here. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/config.jelly b/src/main/resources/com/ibm/devops/dra/PublishSQ/config.jelly deleted file mode 100644 index 6f8d784..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/config.jelly +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/global.jelly b/src/main/resources/com/ibm/devops/dra/PublishSQ/global.jelly deleted file mode 100644 index b9ecd47..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/global.jelly +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQAuthToken.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQAuthToken.html deleted file mode 100644 index 2070328..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQAuthToken.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Enter your API token that SonarQube generated for you. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQHostName.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQHostName.html deleted file mode 100644 index f669942..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQHostName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the hostname of the server that your SonarQube instance runs on. Do not enter a trailing slash. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQProjectKey.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQProjectKey.html deleted file mode 100644 index cc3785b..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-SQProjectKey.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the key of the SonarQube project that you wish to scan. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-additionalBuildInfo.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-additionalBuildInfo.html deleted file mode 100644 index 999c790..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-additionalBuildInfo.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box if you want to set your own build number -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-applicationName.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-applicationName.html deleted file mode 100644 index 5faec8c..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-applicationName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type a name for the application that information is being uploaded for. Use this application name when you configure DevOps Insights gates. You can use an environment variable, such as $APP_NAME. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildJobName.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildJobName.html deleted file mode 100644 index 08847b7..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildJobName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Enter the name of the build job that triggers this test job. You can use an environment variable, such as $BUILD_JOB. -
diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildNumber.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildNumber.html deleted file mode 100644 index 6ca7fb8..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-buildNumber.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Specify the custom build number for this job. You can define this number as an environment variable. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-credentialsId.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-credentialsId.html deleted file mode 100644 index 8fef5fe..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-credentialsId.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a Bluemix ID from the menu. If no Bluemix IDs are in the menu, click Add to add one. Click Test Connection to verify the selected credentials. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-orgName.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-orgName.html deleted file mode 100644 index dfe4277..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-orgName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the Bluemix organization that you want to use. You can type the name here or use an environment variable, such as $ORG_NAME, that is defined elsewhere. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-toolchainName.html b/src/main/resources/com/ibm/devops/dra/PublishSQ/help-toolchainName.html deleted file mode 100644 index 0aec8dc..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishSQ/help-toolchainName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a toolchain. If you have not created a toolchain yet, create one here. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/config.jelly b/src/main/resources/com/ibm/devops/dra/PublishTest/config.jelly deleted file mode 100644 index 03a5d8a..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/config.jelly +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/global.jelly b/src/main/resources/com/ibm/devops/dra/PublishTest/global.jelly deleted file mode 100644 index acaddf4..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/global.jelly +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalBuildInfo.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalBuildInfo.html deleted file mode 100644 index 999c790..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalBuildInfo.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select this check box if you want to set your own build number -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalContents.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalContents.html deleted file mode 100644 index ea3336e..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalContents.html +++ /dev/null @@ -1,20 +0,0 @@ - - -
- Enter the test result file location relative to the root directory. The result file must contain results in the format that you selected for the metric type. This field supports wildcards and environment variables. - If you leave this field empty, DevOps Insights generates a simple test report that is based on job status. - Mocha, KarmaMocha, Istanbul, and BlanketJS test results must be in the JSON format. - xUnit test results must be in the XML format. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalLifecycleStage.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalLifecycleStage.html deleted file mode 100644 index bb6b5c3..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalLifecycleStage.html +++ /dev/null @@ -1,22 +0,0 @@ - - -
- Select the type of test. Your tests must correspond to rules in policies. -
    - Supported formats: -
  • Code coverage: Istanbul, BlanketJS
  • -
  • Unit and functional verification tests: Mocha, xUnit, and Karma Mocha
  • -
-
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalUpload.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalUpload.html deleted file mode 100644 index 5702e51..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-additionalUpload.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Optional: You can upload another test result file and select another metric type in this job. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-applicationName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-applicationName.html deleted file mode 100644 index 3f5adfd..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-applicationName.html +++ /dev/null @@ -1,18 +0,0 @@ - - -
- Type a name for the application that information is being uploaded for. Use this application name when you configure DevOps Insights gates. You can use an environment variable, such as $APP_NAME. -
- diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildJobName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildJobName.html deleted file mode 100644 index 4a4049b..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildJobName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Enter the name of the build job that triggers this test job. You can use an environment variable, such as $BUILD_JOB. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildNumber.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildNumber.html deleted file mode 100644 index 6ca7fb8..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-buildNumber.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Specify the custom build number for this job. You can define this number as an environment variable. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-contents.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-contents.html deleted file mode 100644 index ea3336e..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-contents.html +++ /dev/null @@ -1,20 +0,0 @@ - - -
- Enter the test result file location relative to the root directory. The result file must contain results in the format that you selected for the metric type. This field supports wildcards and environment variables. - If you leave this field empty, DevOps Insights generates a simple test report that is based on job status. - Mocha, KarmaMocha, Istanbul, and BlanketJS test results must be in the JSON format. - xUnit test results must be in the XML format. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-credentialsId.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-credentialsId.html deleted file mode 100644 index cd32d9a..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-credentialsId.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a Bluemix ID from the menu. If no Bluemix IDs are in the menu, click Add to add one. Click Test Connection to verify the selected credentials. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-envName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-envName.html deleted file mode 100644 index c89fb18..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-envName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the deployment environment where the tests are run. This name must match the environment name that is used in upstream test or deployment information upload jobs, such as "STAGING" or "PRODUCTION." -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-environment.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-environment.html deleted file mode 100644 index 4416bf6..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-environment.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Choose the environment that the test runs on. If the test runs during the build process, click Build environment.>. If the test runs on a deployed application, click Deploy environment and enter the environment name. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-lifecycleStage.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-lifecycleStage.html deleted file mode 100644 index bb6b5c3..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-lifecycleStage.html +++ /dev/null @@ -1,22 +0,0 @@ - - -
- Select the type of test. Your tests must correspond to rules in policies. -
    - Supported formats: -
  • Code coverage: Istanbul, BlanketJS
  • -
  • Unit and functional verification tests: Mocha, xUnit, and Karma Mocha
  • -
-
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-orgName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-orgName.html deleted file mode 100644 index f8feb78..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-orgName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Type the name of the Bluemix organization that you want to use. You can type the name here or use an environment variable, such as $ORG_NAME, that is defined elsewhere. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-policyName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-policyName.html deleted file mode 100644 index 5875757..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-policyName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- To evaluate test results in this job, select this check box and select a policy. The job uploads information and acts as a gate. You can create more policies in DevOps Insights. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/dra/PublishTest/help-toolchainName.html b/src/main/resources/com/ibm/devops/dra/PublishTest/help-toolchainName.html deleted file mode 100644 index 42b2702..0000000 --- a/src/main/resources/com/ibm/devops/dra/PublishTest/help-toolchainName.html +++ /dev/null @@ -1,17 +0,0 @@ - - -
- Select a toolchain. If you have not created a toolchain yet, create one here. -
\ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/notification/OTCNotifier/config.jelly b/src/main/resources/com/ibm/devops/notification/OTCNotifier/config.jelly deleted file mode 100644 index b587e69..0000000 --- a/src/main/resources/com/ibm/devops/notification/OTCNotifier/config.jelly +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/com/ibm/devops/notification/OTCNotifier/help.html b/src/main/resources/com/ibm/devops/notification/OTCNotifier/help.html deleted file mode 100644 index 4f7de10..0000000 --- a/src/main/resources/com/ibm/devops/notification/OTCNotifier/help.html +++ /dev/null @@ -1,21 +0,0 @@ - - -
- Please create a String Parameter named "IBM_CLOUD_DEVOPS_WEBHOOK_URL" and set the default value to the webhook that you'd like to send messages to. -
-
-
- Select Track deployment of code changes check box to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. -
\ No newline at end of file diff --git a/src/main/resources/index.jelly b/src/main/resources/index.jelly deleted file mode 100644 index fd75fab..0000000 --- a/src/main/resources/index.jelly +++ /dev/null @@ -1,21 +0,0 @@ - - - - -
- IBM® Cloud DevOps aggregates and provides visualizations of the indications of a continuous delivery project’s health. Use its built-in dashboards and data reporting services to learn where you most need to improve your build, test, and delivery processes. You can also define test coverage policies to prevent bad code from being promoted to critical environments. -
diff --git a/src/main/resources/plugin.properties b/src/main/resources/plugin.properties deleted file mode 100644 index defbd48..0000000 --- a/src/main/resources/plugin.properties +++ /dev/null @@ -1 +0,0 @@ -version=${project.version} diff --git a/src/test/java/com/ibm/devops/dra/UtilTest.java b/src/test/java/com/ibm/devops/dra/UtilTest.java deleted file mode 100644 index 316b1cb..0000000 --- a/src/test/java/com/ibm/devops/dra/UtilTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ibm.devops.dra; - -import org.junit.Test; -import static junit.framework.TestCase.*; - - -public class UtilTest { - - @Test - public void testIsNullOrEmpty() { - Boolean result = Util.isNullOrEmpty(""); - assertTrue(result); - - result = Util.isNullOrEmpty(null); - assertTrue(result); - - result = Util.isNullOrEmpty("Not Null"); - assertFalse(result); - } - - @Test - public void testAllNotNullOrEmpty() { - Boolean result = Util.allNotNullOrEmpty("Not Null", "Not Null", "Not Null", ""); - assertFalse(result); - - result = Util.allNotNullOrEmpty("Not Null", "Not Null", "Not Null", null); - assertFalse(result); - - result = Util.allNotNullOrEmpty("Not Null", "Not Null", "Not Null", "Not Null"); - assertTrue(result); - } -} diff --git a/src/test/java/com/ibm/devops/notification/EventHandlerTest.java b/src/test/java/com/ibm/devops/notification/EventHandlerTest.java deleted file mode 100644 index 5bbc88b..0000000 --- a/src/test/java/com/ibm/devops/notification/EventHandlerTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.model.*; -import hudson.tasks.Publisher; -import hudson.util.DescribableList; -import org.junit.Test; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.*; -import static junit.framework.TestCase.*; - -public class EventHandlerTest { - - @Test - public void testFindPublisher() { - OTCNotifier otcNotifier = mock(OTCNotifier.class); - AbstractBuild r = mock(AbstractBuild.class); - AbstractProject project = mock(AbstractProject.class); - DescribableList> describableList = mock(DescribableList.class); - ArrayList publisherList = new ArrayList(); - - publisherList.add(otcNotifier); - when(r.getProject()).thenReturn(project); - when(project.getPublishersList()).thenReturn(describableList); - when(describableList.toList()).thenReturn(publisherList); - - assertEquals(otcNotifier, EventHandler.findPublisher(r)); - } - - @Test - public void testGetEnv() throws IOException, InterruptedException { - AbstractBuild r = mock(AbstractBuild.class); - TaskListener listener = mock(TaskListener.class); - PrintStream printStream = mock(PrintStream.class); - - when(r.getEnvironment(listener)).thenReturn(new EnvVars()); - assertNotNull(EventHandler.getEnv(r, listener, printStream)); - - when(r.getEnvironment(listener)).thenThrow(new IOException("...")); - assertNull(EventHandler.getEnv(r, listener, printStream)); - - reset(r); - when(r.getEnvironment(listener)).thenThrow(new InterruptedException("...")); - assertNull(EventHandler.getEnv(r, listener, printStream)); - } - - @Test - public void testIsRelevant(){ - OTCNotifier notifier = mock(OTCNotifier.class); - String[] phases = {"STARTED", "COMPLETED", "FINALIZED"};//check all possible phases - - when(notifier.getOnStarted()).thenReturn(true); - when(notifier.getOnCompleted()).thenReturn(true); - when(notifier.getOnFinalized()).thenReturn(true); - when(notifier.getFailureOnly()).thenReturn(false); - - assertFalse(EventHandler.isRelevant(notifier, "BAD_PHASE", null));//check bad phase - assertTrue(EventHandler.isRelevant(notifier, "STARTED", null));//check started with no status - - for(String phase : phases){ - assertTrue(EventHandler.isRelevant(notifier, phase, Result.SUCCESS)); - } - - for(String phase : phases){ - assertTrue(EventHandler.isRelevant(notifier, phase, Result.FAILURE)); - } - - //Check failures only - when(notifier.getFailureOnly()).thenReturn(true); - - for(String phase : phases){ - assertFalse(EventHandler.isRelevant(notifier, phase, Result.SUCCESS)); - } - - for(String phase : phases){ - assertTrue(EventHandler.isRelevant(notifier, phase, Result.FAILURE)); - } - } - - @Test - public void testGetWebhookFromEnv() { - Map m = new HashMap<>(); - EnvVars envVars = new EnvVars(m); - - assertNull(Util.getWebhookUrl(envVars)); - - m.put("ICD_WEBHOOK_URL", "compatibility_test"); - envVars = new EnvVars(m); - assertEquals("compatibility_test", Util.getWebhookUrl(envVars)); - - m.put("IBM_CLOUD_DEVOPS_WEBHOOK_URL", "test"); - envVars = new EnvVars(m); - assertEquals("test", Util.getWebhookUrl(envVars)); - } -} diff --git a/src/test/java/com/ibm/devops/notification/MessageHandlerTest.java b/src/test/java/com/ibm/devops/notification/MessageHandlerTest.java deleted file mode 100644 index 5ea0587..0000000 --- a/src/test/java/com/ibm/devops/notification/MessageHandlerTest.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - - - Copyright 2017 IBM Corporation - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - */ - -package com.ibm.devops.notification; - -import com.ibm.devops.dra.Util; -import hudson.EnvVars; -import hudson.model.Job; -import hudson.model.Run; -import jenkins.model.Jenkins; -import net.sf.json.JSONObject; -import org.apache.http.StatusLine; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -import static org.mockito.Mockito.*; -import static junit.framework.TestCase.*; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({Jenkins.class, Job.class, HttpClients.class, CloseableHttpResponse.class}) -public class MessageHandlerTest { - private Jenkins jenkins = mock(Jenkins.class); - - @Before - public void setUp() throws Exception { - PowerMockito.mockStatic(Jenkins.class); - PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins); - PowerMockito.when(jenkins.getRootUrl()).thenReturn("http://localhost:1234/"); - } - - @Test - public void testBuildMessage() { - String phase = "COMPLETED"; - String result = "SUCCESS"; - - Run r = mock(Run.class); - EnvVars envVars = mock(EnvVars.class); - Job job = PowerMockito.mock(Job.class); - - when(r.getParent()).thenReturn(job); - when(r.getNumber()).thenReturn(0); - when(r.getQueueId()).thenReturn((long)0); - when(r.getUrl()).thenReturn("job/test/1/"); - when(r.getDuration()).thenReturn((long)0); - when(job.getName()).thenReturn("test"); - when(job.getUrl()).thenReturn("job/test/"); - when(envVars.get("GIT_COMMIT")).thenReturn("commit"); - when(envVars.get("GIT_BRANCH")).thenReturn("branch"); - when(envVars.get("GIT_PREVIOUS_COMMIT")).thenReturn("previous"); - when(envVars.get("GIT_PREVIOUS_SUCCESSFUL_COMMIT")).thenReturn("previous_success"); - when(envVars.get("GIT_URL")).thenReturn("url"); - when(envVars.get("GIT_COMMITTER_NAME")).thenReturn("committer"); - when(envVars.get("GIT_COMMITTER_EMAIL")).thenReturn("committer_email"); - when(envVars.get("GIT_AUTHOR_NAME")).thenReturn("author"); - when(envVars.get("GIT_AUTHOR_EMAIL")).thenReturn("author_email"); - - JSONObject message = new JSONObject(); - JSONObject build = new JSONObject(); - JSONObject scm = new JSONObject(); - - scm.put("git_commit", envVars.get("GIT_COMMIT")); - scm.put("git_branch", envVars.get("GIT_BRANCH")); - scm.put("git_previous_commit", envVars.get("GIT_PREVIOUS_COMMIT")); - scm.put("git_previous_successful_commit", envVars.get("GIT_PREVIOUS_SUCCESSFUL_COMMIT")); - scm.put("git_url", envVars.get("GIT_URL")); - scm.put("git_committer_name", envVars.get("GIT_COMMITTER_NAME")); - scm.put("git_committer_email", envVars.get("GIT_COMMITTER_EMAIL")); - scm.put("git_author_name", envVars.get("GIT_AUTHOR_NAME")); - scm.put("git_author_email", envVars.get("GIT_AUTHOR_EMAIL")); - - build.put("number", r.getNumber()); - build.put("queue_id", r.getQueueId()); - build.put("phase", phase); - build.put("url", r.getUrl()); - build.put("full_url", Jenkins.getInstance().getRootUrl() + r.getUrl()); - build.put("status", result); - build.put("duration", r.getDuration()); - build.put("scm", scm); - message.put("name", job.getName()); - message.put("url", job.getUrl()); - message.put("build", build); - - assertEquals(message, MessageHandler.buildMessage(r, envVars, phase, result)); - - build.put("scm", new JSONObject()); - message.put("build", build); - - assertEquals(message, MessageHandler.buildMessage(r, null, phase, result)); - } - - @Test - public void testPostToWebhook() throws IOException { - HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class); - CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); - CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); - PowerMockito.mockStatic(HttpClients.class); - StatusLine statusLine = mock(StatusLine.class); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream(baos); - String content; - JSONObject message = new JSONObject(); - - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setSocketTimeout(5000) - .setConnectTimeout(5000) - .setConnectionRequestTimeout(5000) - .build(); - when(HttpClients.custom()).thenReturn(httpClientBuilder); - when(httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig).build()).thenReturn(httpClient); - when(httpClient.execute(any(HttpPost.class))).thenReturn(response); - when(response.getStatusLine()).thenReturn(statusLine); - when(statusLine.toString()).thenReturn("200"); - - assertTrue(Util.isNullOrEmpty("")); - assertTrue(Util.isNullOrEmpty(null)); - - MessageHandler.postToWebhook("", false, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - - assertTrue(content.contains("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set.")); - - MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook.")); - - when(statusLine.toString()).thenReturn("400"); - MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] Message failed, response status:")); - - when(httpClient.execute(any(HttpPost.class))).thenThrow(new IOException("...")); - MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] IOException, could not post to webhook:")); - } - - @Test - public void testPostDeployableMessageToWebhook() throws IOException { - HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class); - CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); - CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); - PowerMockito.mockStatic(HttpClients.class); - StatusLine statusLine = mock(StatusLine.class); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream(baos); - String content; - JSONObject message = new JSONObject(); - - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setSocketTimeout(5000) - .setConnectTimeout(5000) - .setConnectionRequestTimeout(5000) - .build(); - when(HttpClients.custom()).thenReturn(httpClientBuilder); - when(httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig).build()).thenReturn(httpClient); - when(httpClient.execute(any(HttpPost.class))).thenReturn(response); - when(response.getStatusLine()).thenReturn(statusLine); - when(statusLine.toString()).thenReturn("200"); - - assertTrue(Util.isNullOrEmpty("")); - assertTrue(Util.isNullOrEmpty(null)); - - MessageHandler.postToWebhook("", true, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - System.out.println("content: " + content); - assertTrue(content.contains("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set.")); - - MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook.")); - - when(statusLine.toString()).thenReturn("400"); - MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] Message failed, response status:")); - - when(httpClient.execute(any(HttpPost.class))).thenThrow(new IOException("...")); - MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] IOException, could not post to webhook:")); - - message = new JSONObject(); - message.put("Org" , "{\"Name\": \"darth_vador@ibm.com\", \"Guid\": \"1b45b640-ff52-4f94-8009-9af44aa9f9c8\"}"); - message.put("Space" , "{\"Name\": \"dev\", \"Guid\": \"838b41a6-58e0-4c05-aaf4-817925d42332\"}"); - message.put("App" , "{\"Name\": \"node-hello-world\", \"Guid\": \"a7820d14-9d5d-40c7-a58c-43caeaf8cb75\"}"); - message.put("ApiEndpoint" , "https://api.stage1.ng.bluemix.net"); - message.put("Method" , "POST"); - message.put("GitData" , "[{\"GitURL\": \"https://github.com/dvador/simple-node-app.git\", \"GitBranch\": \"origin/master\", \"GitCommitID\": \"590c229c64ef246e5742744449963dc74493cb8a\"}]"); - - when(httpClient.execute(any(HttpPost.class))).thenReturn(response); - MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream); - content = new String(baos.toByteArray(), StandardCharsets.UTF_8); - assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook.")); - } -}