node {
   def mvnHome
   stage('Preparation') { // for display purposes
      // Get some code from a GitHub repository
      git 'https://github.com/cschneider4711/Marathon.git'
      // Get the Maven tool.
      // ** NOTE: This 'M3' Maven tool must be configured
      // **       in the global configuration.           
      mvnHome = tool 'M3'
   }


   stage('Build') {
      // Run the maven build
      withEnv(["MVN_HOME=$mvnHome"]) {
         if (isUnix()) {
            sh '"$MVN_HOME/bin/mvn" -Dmaven.test.failure.ignore clean package'
         } else {
            bat(/"%MVN_HOME%\bin\mvn" -Dmaven.test.failure.ignore clean package/)
         }
      }
   }
   

   stage ('Code Analysis') {
      withEnv(["MVN_HOME=$mvnHome"]) {
         sh '$MVN_HOME/bin/mvn --batch-mode -V -U -e spotbugs:spotbugs -Dspotbugs.suppression.filename=spotbugs-suppressions-marathon.xml'
      }
   }
   
   
   stage('Integration Test Startup') {
      sh 'cd integration; ./start-integration.sh' 
   }
   stage('Dynamic Scan Execution') {
      sh 'echo "Just in case and ignore the exit code of `curl -s http://localhost:7777/JSON/core/action/shutdown/`"'
      script {
          startZap(host: "127.0.0.1", port: 7777, timeout:600, zapHome: "/opt/zap", allowedHosts:['localhost'])
      }
      sh 'curl -s http://localhost:7777/JSON/ascan/action/removeScanPolicy/?zapapiformat=JSON\\&scanPolicyName=marathon-policy'
      sh 'curl -s http://localhost:7777/JSON/ascan/action/importScanPolicy/?zapapiformat=JSON\\&path=${WORKSPACE}/integration/policies/zap/marathon-policy.policy'
      sh 'curl -s http://localhost:7777/JSON/ascan/action/setOptionDefaultPolicy/?zapapiformat=JSON\\&String=marathon-policy'
      sh 'curl -s http://localhost:7777/JSON/ascan/action/setOptionAttackPolicy/?zapapiformat=JSON\\&String=marathon-policy'
      sh 'curl -s http://localhost:7777/JSON/context/action/newContext/?zapapiformat=JSON\\&contextName=marathon'
      sh 'curl -s http://localhost:7777/JSON/context/action/includeInContext/?zapapiformat=JSON\\&contextName=marathon\\&regex=http://localhost:9090/.*'
      sh 'curl -s http://localhost:7777/JSON/core/action/setMode/?zapapiformat=JSON\\&mode=attack'
      sh 'curl -s http://localhost:7777/JSON/script/action/load/?zapapiformat=JSON\\&scriptName=marathon-runner-workflow\\&scriptType=standalone\\&scriptEngine=Mozilla+Zest\\&fileName=${WORKSPACE}/zest/marathon-local-integration-port-9090.zst\\&scriptDescription=\\&charset='
      sh 'curl -s http://localhost:7777/JSON/script/action/runStandAloneScript/?zapapiformat=JSON\\&scriptName=marathon-runner-workflow'
      // checking for active scan finish      
      for (int i = 0; i < 20; i++) {
        sh 'sleep 30'
        def ATTACK_MODE_QUEUE = sh ( script: "curl -s http://localhost:7777/JSON/ascan/view/attackModeQueue/?zapapiformat=JSON", returnStdout: true )
        echo "Checking queue size if active scan has finished: ${ATTACK_MODE_QUEUE}"
        if (ATTACK_MODE_QUEUE == '{"attackModeQueue":"-1"}') {
            echo "Active scan has finished"
            sh 'curl -s http://localhost:7777/JSON/core/view/alertsSummary/?zapapiformat=JSON\\&baseurl='
            break;
        }
      }
   }

   stage('Integration Test Shutdown') {
      sh 'cd integration; ./stop-integration.sh' 
   }
      
   stage("Dependency Check") { 
       step([$class: 'DependencyCheckBuilder', 
       datadir: '', 
       hintsFile: '', 
       includeCsvReports: false, 
       includeHtmlReports: true, 
       includeJsonReports: false, 
       isAutoupdateDisabled: false, 
       outdir: '', 
       scanpath: '', 
       skipOnScmChange: false, 
       skipOnUpstreamChange: false, 
       suppressionFile: 'integration/false-positives/depcheck-suppressions.xml', 
       zipExtensions: '']) 
   }   
   

   stage('Results') {
      junit '**/target/surefire-reports/TEST-*.xml'
      archiveArtifacts 'target/*.war'
      recordIssues tool: spotBugs(), healthy: 1, unhealthy: 7, minimumSeverity: 'HIGH', qualityGates: [[threshold: 3, type: 'TOTAL_HIGH', unstable: true]]
      dependencyCheckPublisher pattern: 'dependency-check-report.xml', unstableTotalHigh: '1'
      sh 'cp integration/false-positives/zap-scan-suppressions.json ../../jobs/marathon/builds/$BUILD_NUMBER/.'
      script {
          archiveZap(failAllAlerts: 0, failHighAlerts: 1, failMediumAlerts: 0, failLowAlerts: 0  
               , falsePositivesFilePath: 'zap-scan-suppressions.json')
      }
   }
}