package propel

import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey
import com.cloudbees.plugins.credentials.CredentialsScope
import com.cloudbees.plugins.credentials.CredentialsProvider
import hudson.plugins.git.BranchSpec
import hudson.plugins.git.GitSCM
import hudson.plugins.git.SubmoduleConfig
import hudson.plugins.git.UserRemoteConfig
import hudson.plugins.git.extensions.GitSCMExtension
import hudson.scm.SCM
import hudson.security.*
import jenkins.branch.OrganizationFolder
import jenkins.scm.api.SCMSourceOwner
import jenkins.scm.api.SCMSourceOwners
import org.jenkinsci.plugins.GithubSecurityRealm
import org.jenkinsci.plugins.github_branch_source.GitHubSCMNavigator
import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration
import org.jenkinsci.plugins.workflow.libs.SCMRetriever
import org.jfrog.hudson.ArtifactoryServer
import org.jfrog.hudson.CredentialsConfig
import org.jfrog.hudson.util.Credentials
import java.util.logging.Logger
import jenkins.model.*
import hudson.model.*
import org.jenkinsci.plugins.simpletheme.JsUrlThemeElement
import org.jenkinsci.plugins.simpletheme.CssUrlThemeElement
import hudson.model.*
import jenkins.model.*
import hudson.plugins.ec2.*
import com.amazonaws.services.ec2.model.*
import groovy.json.JsonSlurper

import org.csanchez.jenkins.plugins.kubernetes.*
import org.csanchez.jenkins.plugins.kubernetes.model.*
import org.csanchez.jenkins.plugins.kubernetes.volumes.*

abstract class Build {

    Logger logger = Logger.getLogger('PropelGroovyConsumer')
    String metaData = ''
    Map<String,String> metaDataMap = new HashMap<>()
    String metaDataDefault = ''

    //############################################Artifactory config############################################
    boolean addOrUpdateArtifactoryServer(String id, String url, String userId, String pwd)  throws Throwable{
        try {
            com.cloudbees.plugins.credentials.Credentials cred = addOrUpdateStandardCredential(id, userId, pwd)
            logger.info('[addOrUpdateArtifactoryServer] Found in art : ' + cred.id)
            if (cred) {
                if (removeArtifactoryServer(id)) {
                    def env = System.getenv()
                    def inst = Jenkins.getInstance()
                    def artifactoryBuilder = inst.getDescriptor('org.jfrog.hudson.ArtifactoryBuilder')
                    artifactoryBuilder.setUseCredentialsPlugin(true)
                    def deployerCred = new CredentialsConfig(new Credentials(userId, pwd), id, false)
                    def resolverCredentials = new CredentialsConfig(new Credentials(userId, pwd), id, false)
                    def serverInstance = new ArtifactoryServer(id, url, deployerCred, resolverCredentials, 300, false, 3)
                    def slist = artifactoryBuilder.getArtifactoryServers()
                    if (slist == null) {
                        slist = new ArrayList<ArtifactoryServer>()
                    }
                    slist.add(serverInstance)
                    artifactoryBuilder.setArtifactoryServers(slist)
                    artifactoryBuilder.save()
                    logger.info('[addOrUpdateArtifactoryServer] Added artifactory server info :' + id)
                    return true
                }
            }else {
                logger.info('[addOrUpdateArtifactoryServer] Could not create cred :' + id)
                return false
            }
        } catch (Throwable t) {
            logger.warning('[addOrUpdateArtifactoryServer] ' + t.getMessage())
            return false
        }
    }
    boolean removeArtifactoryServer(String id) throws Throwable{
        try {
            logger.info('[removeArtifactoryServer] Inside remove')
            def env = System.getenv()
            def inst = Jenkins.getInstance()
            def artifactoryBuilder = inst.getDescriptor('org.jfrog.hudson.ArtifactoryBuilder')
            def serverList = artifactoryBuilder.getArtifactoryServers()
            if (serverList == null) {
                serverList = new ArrayList<ArtifactoryServer>()
            }
            def copyServerList = serverList.clone()
            for (ArtifactoryServer server : serverList) {
                logger.info('[removeArtifactoryServer] Inside remove : art server id : ' + server.id)
                if (server.id == id) {
                    copyServerList.remove(server)
                    logger.info('[removeArtifactoryServer] Removed Artifactory server :' + id)
                }
            }
            artifactoryBuilder.setArtifactoryServers(copyServerList)
            artifactoryBuilder.save()
            logger.info('[removeArtifactoryServer] After saving artifactory after remove')
            return true
        } catch (Throwable t) {
            t.printStackTrace()
            logger.warning('[removeArtifactoryServer]' + t.getMessage())
            return false
        }
        return true
    }

    //############################################Credential config############################################
    com.cloudbees.plugins.credentials.Credentials addOrUpdateStandardCredential(String id, String userId, String pwd) throws Throwable {
        logger.info('[addOrUpdateStandardCredential] Inside addCred')
        def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
                jenkins.model.Jenkins.instance
        )
        def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
                'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
        )[0].getStore()

        def c = creds.findResult { it.id == id ? it : null }
        if (c) {
            logger.info("[addOrUpdateStandardCredential] found credential ${c.id} for username ${c.username}")
            def result = credentials_store.updateCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), c, new com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl(c.scope, c.id, c.description, userId, pwd))
            if (result) {
                logger.info('[addOrUpdateStandardCredential] Updated credential : ' + id)
            } else {
                logger.info('[addOrUpdateStandardCredential] Could not update credential : ' + id)
            }
        } else {
            logger.info("[addOrUpdateStandardCredential] not found credential ${id}")
            def result = credentials_store.addCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), new com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.CredentialsScope.GLOBAL, id, id, userId, pwd))
            if (result) {
                logger.info('[addOrUpdateStandardCredential] Created credential : ' + id)
            } else {
                logger.info('[addOrUpdateStandardCredential] Could not create credential : ' + id)
            }
        }

        creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
                jenkins.model.Jenkins.instance
        )

        def returnCred = creds.findResult { it.id == id ? it : null };
        logger.info('[addOrUpdateStandardCredential] ' + returnCred.id)

        return returnCred
    }
    boolean removeStandardCredential(String id) throws Throwable {
        def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
                jenkins.model.Jenkins.instance
        )
        def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
                'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
        )[0].getStore()
        def c = creds.findResult { it.id == id ? it : null }
        if (c) {
            logger.info("[removeStandardCredential] found credential ${c.id} for username ${c.username}")
            def result = credentials_store.removeCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), c)
            if (result) {
                logger.info("[removeStandardCredential] deleted for ${id}")
                return true
            } else {
                logger.info("[removeStandardCredential] failed to delete for ${id}")
                return false
            }
        }
        return false
    }

    com.cloudbees.plugins.credentials.Credentials addOrUpdateEC2SSHCredential() throws Throwable {
        logger.info('[addOrUpdateEC2SSHCredential] Inside addCred')
        def creds = CredentialsProvider.lookupCredentials(
                SSHUserPrivateKey.class,
                jenkins.model.Jenkins.instance
        )
        def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
                'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
        )[0].getStore()

        def privateKey = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(
        '''
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAn8EUmtLsmYtqGSoHyRdMORYdeOXGwGLH4/NZRmMr7CTF0nqa
yjuq41JCSnhNC1ScKu7mlASfoWZWibMmSiMhHzCNlN7vFIfGd1nyFYz1r2pjqNFE
6iz5i8shIB4NNzsund+TvN2OOebIqILXXC1VQE1ygnkGM8dYtg/Gla/dNbkVrsre
C0yHZNcwg/vEidewNULx5KhzK4w/7DnKlAMqTMG8GDhp9Z8qdx+cuZsEo3YF6xee
HTihHCov/cHv+mc1GUdAV2/pSrc5XUKRAyOucGDcooaS/xuGhGlulNopBOAsdrF/
7BF41V4IIGEjzIj8cMKvXo6s/fjCHVxp49n6uQIDAQABAoIBAF7f4yXDiCH0CvGg
5XjGbk0k1iH7jBqrT30QA3/q26XlfNpwV8cswmM4cggaA99rw0c4FBXp3QeUaGZk
z6ON01jbk+nKr//oVrSA5WVpDmu76i3TAnN0fEtKOoUBc+XOLvQxWGL8zT+T0K1K
7y1d+tgyZoQX7dgIVqXhHpW9GMmTDD45tfL6JT4uTHcRisb9w5LLxWG3xSKvoXgu
jtnTPAMHi7npOKCj6KBQqBMWUVKTwVLuJAph+1bCrz+dezqLT/1EMcaOZs8t8aRj
JyINXoj+PdhBPinGAf3k4vUfcw0bIyAah2DlajqNCFwGZelb08iUYG2WOdIfXZKW
BTtEQwUCgYEA6KHR/eyJ6bFxWgclrtWg8W53pm2tH7UhqG2XfPxRg2mjwdhOQots
+02fWqbjxDmDc9f8wtspIjnmGekVFU8RFQL6Dy0A6WfcZvJqVejG7ckE7GXg2SdP
sriIBN0tnOjUbz3DfLC8pYkRL8flZNp/BmFd7veWMLNEWgac+rTsgEsCgYEAr80w
8LeQ/OZ5evk3IQ9GVipcZfE44pdHWwDY3NVN3Dp2LrOeVslPBJXAG/O4bSC9gttF
zPmafCz3M+GQVeJQRkWXjmBIJPCGN7ou02pC9xYNVtkaoV/0UctSfjgg4z5fSLpe
gn7epd/jqoOFZTfC54BplFBhJJD/FrTpR/XRtosCgYAl/sgdgRTFZoXs/l3ZQGsZ
A8HnHOK52wu0RrIHZ+6oWAi3EG030S3rnbH5TGjHE920fgJ6kPEW9f3vHXKkGFXh
6KqO7/rGJICLD+zuOybCj6KOOdWPoiwSNLGCmd1pU13fDWdwZi1pnAmClFOTNVyp
3h1Jeoa9TYpMaegZypMWIQKBgQClKl6EibIKKG6Rfnqw8KzgX0QX8p3DJOXBNfaI
404XTkWictacKt22LQskN8JZpJznyCK4BPmDGKvXbmAwkENjAhb1iLe/HMq8qIs9
zWPEyE8X/TjrzD66ag/CzfD4Dq1uosoQSCneJY67sH0vL0hKP3byBOJ/fEpshuN0
3Bp/KQKBgA2DBhEPt7Zi6tWqrNxeZWPj6Yk1g1mRooGmDIGQgRF1+yl4+Pe+Ogfd
s68RYLbRQtoTPoydiJ10TJU2XfsKVoXzpFwfTT/45VdY6CQIwhwOj739HIkXbgrp
mp0OKJOZZfZy6rdTJqlJLjTR/y504gvU7lSWHPSVmc2nX8Xxf9ww
-----END RSA PRIVATE KEY-----
    '''
        )

        def sshKey = new BasicSSHUserPrivateKey(
          CredentialsScope.GLOBAL,
          "EC2Key",
          "",
          privateKey,
          "",
          "key"
        )


        def c = creds.findResult { it.id == "EC2Key" ? it : null }
        if (c) {
            logger.info("[addOrUpdateEC2SSHCredential] found credential ${c.id} for username ${c.username}")
            def result = credentials_store.updateCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), c, sshKey)
            if (result) {
                logger.info('[addOrUpdateEC2SSHCredential] Updated credential : key')
            } else {
                logger.info('[addOrUpdateEC2SSHCredential] Could not update credential : key')
            }
        } else {
            logger.info("[addOrUpdateEC2SSHCredential] not found credential")
            def result = credentials_store.addCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), sshKey)
            if (result) {
                logger.info('[addOrUpdateEC2SSHCredential] Created credential : key')            
            } else {
                logger.info('[addOrUpdateEC2SSHCredential] Could not create credential : key')           
            }
        }

        def creds2 = CredentialsProvider.lookupCredentials(
                SSHUserPrivateKey.class,
                jenkins.model.Jenkins.instance
        )
        def returnCred = creds2.findResult { it.id == "EC2Key" ? it : null };
        logger.info('[addOrUpdateEC2SSHCredential] ' + returnCred.id)

        return returnCred
    }
    boolean removeSSHCredential() throws Throwable {
        def creds = CredentialsProvider.lookupCredentials(
                SSHUserPrivateKey.class,
                jenkins.model.Jenkins.instance
        )
        def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
                'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
        )[0].getStore()
        def c = creds.findResult { it.id == "EC2Key" ? it : null }
        if (c) {
            logger.info("[removeSSHCredential] found credential ${c.id}")
            def result = credentials_store.removeCredentials(com.cloudbees.plugins.credentials.domains.Domain.global(), c)
            if (result) {
                logger.info("[removeSSHCredential] deleted for ${c.id}")
                return true
            } else {
                logger.info("[removeSSHCredential] failed to delete for ${c.id}")
                return false
            }
        }
        return false
    }

    //############################################Authorization config############################################
    boolean configureDevOpsAdmin(String addedIds, String deletedIds) throws Throwable{
        if (addedIds == null) {
            addedIds = ''
        }
        if (deletedIds == null) {
            deletedIds = ''
        }

        addedIds = addedIds.trim()
        deletedIds = deletedIds.trim()

        def addedIdsArr = addedIds.split(',')
        Set<String> addedIdsSet = new HashSet<String>(Arrays.asList(addedIdsArr))
        def deletedIdsArr = deletedIds.split(',')
        Set<String> deletedIdsSet = new HashSet<String>(Arrays.asList(deletedIdsArr))

        if (addedIds.size() == 0 && deletedIds == 0) {
            return false
        }
        logger.info('[configureDevOpsAdmin] added userIds : ' + addedIds)
        logger.info('[configureDevOpsAdmin] deleted userIds : ' + deletedIds)

        def ast = Jenkins.getActiveInstance().getAuthorizationStrategy()
        if (ast.getClass().getName().contains('GlobalMatrixAuthorizationStrategy')) {
            def existingSt = (GlobalMatrixAuthorizationStrategy)ast
            Map<Permission, Set<String>> oldPermissions = existingSt.getGrantedPermissions()
            Map<Permission, Set<String>> newPermissions = new HashMap<>()
            for (Permission permission : oldPermissions.keySet()) {
                Set<String> setOfUsers = oldPermissions.get(permission)
                if (permission.equals(Jenkins.ADMINISTER)) {
                    for (String deleteId :deletedIdsSet) {
                        if (setOfUsers.contains(deleteId)) {
                            setOfUsers.remove(deleteId)
                        }
                    }
                    for (String addId :addedIdsSet) {
                        if (!setOfUsers.contains(addId)) {
                            setOfUsers.add(addId)
                        }
                    }
                    if (setOfUsers.size() > 0) {
                        newPermissions.put(permission, setOfUsers)
                    }
                }
                else {
                    newPermissions.put(permission, setOfUsers)
                }
            }
            setPermissions(newPermissions, ast)
        }
        return true
    }
    boolean configureDeveloper(String addedIds, String deletedIds) throws Throwable{
        if (addedIds == null) {
            addedIds = ''
        }
        if (deletedIds == null) {
            deletedIds = ''
        }

        addedIds = addedIds.trim()
        deletedIds = deletedIds.trim()

        def addedIdsArr = addedIds.split(',')
        Set<String> addedIdsSet = new HashSet<String>(Arrays.asList(addedIdsArr))
        def deletedIdsArr = deletedIds.split(',')
        Set<String> deletedIdsSet = new HashSet<String>(Arrays.asList(deletedIdsArr))

        logger.info('[configureDeveloper] added userIds : ' + addedIds)
        logger.info('[configureDeveloper] deleted userIds : ' + deletedIds)
        def ast = Jenkins.getActiveInstance().getAuthorizationStrategy()
        if (ast.getClass().getName().contains('GlobalMatrixAuthorizationStrategy')) {
            def existingSt = (GlobalMatrixAuthorizationStrategy) ast
            Map<Permission, Set<String>> oldPermissions = existingSt.getGrantedPermissions()
            Map<Permission, Set<String>> newPermissions = new HashMap<>()
            for (Permission permission : oldPermissions.keySet()) {
                Set<String> setOfUsers = oldPermissions.get(permission)
                for (String deleteId : deletedIdsSet) {
                    if (setOfUsers.contains(deleteId) && isDevPermission(permission)) {
                        setOfUsers.remove(deleteId)
                    }
                }
                if (setOfUsers.size() > 0) {
                    newPermissions.put(permission, setOfUsers)
                }
            }
            for (PermissionGroup pg : PermissionGroup.getAll()) {
                for (Permission p : pg.getPermissions()) {
                    if (isDevPermission(p)) {
                        if (newPermissions.containsKey(p)) {
                            newPermissions.get(p).addAll(addedIdsSet)
                        }else {
                            newPermissions.put(p, addedIdsSet)
                        }
                    }
                }
            }
            setPermissions(newPermissions, ast)
        }
        return true
    }

    boolean configureViewer(String addedIds, String deletedIds) throws Throwable{
        if (addedIds == null) {
            addedIds = ''
        }
        if (deletedIds == null) {
            deletedIds = ''
        }

        addedIds = addedIds.trim()
        deletedIds = deletedIds.trim()

        def addedIdsArr = addedIds.split(',')
        Set<String> addedIdsSet = new HashSet<String>(Arrays.asList(addedIdsArr))
        def deletedIdsArr = deletedIds.split(',')
        Set<String> deletedIdsSet = new HashSet<String>(Arrays.asList(deletedIdsArr))

        logger.info('[configureViewer] added userIds : ' + addedIds)
        logger.info('[configureViewer] deleted userIds : ' + deletedIds)
        def ast = Jenkins.getActiveInstance().getAuthorizationStrategy()
        if (ast.getClass().getName().contains('GlobalMatrixAuthorizationStrategy')) {
            def existingSt = (GlobalMatrixAuthorizationStrategy) ast
            Map<Permission, Set<String>> oldPermissions = existingSt.getGrantedPermissions()
            Map<Permission, Set<String>> newPermissions = new HashMap<>()
            for (Permission permission : oldPermissions.keySet()) {
                Set<String> setOfUsers = oldPermissions.get(permission)
                for (String deleteId : deletedIdsSet) {
                    if (setOfUsers.contains(deleteId) && isViewerPermission(permission)) {
                        setOfUsers.remove(deleteId)
                    }
                }
                if (setOfUsers.size() > 0) {
                    newPermissions.put(permission, setOfUsers)
                }
            }
            for (PermissionGroup pg : PermissionGroup.getAll()) {
                for (Permission p : pg.getPermissions()) {
                    if (isViewerPermission(p)) {
                        if (newPermissions.containsKey(p)) {
                            newPermissions.get(p).addAll(addedIdsSet)
                        }else {
                            newPermissions.put(p, addedIdsSet)
                        }
                    }
                }
            }
            setPermissions(newPermissions, ast)
        }
        return true
    }

    boolean isViewerPermission(Permission permission) {
        if (permission.equals(Jenkins.READ)) {
            return true
        }

        if (permission.owner.equals(hudson.model.Item.class) && permission.name.equals('Read')) {
            return true
        }
        if (permission.owner.equals(hudson.model.Item.class) && permission.name.equals('ViewStatus')) {
            return true
        }

        return false
    }

    boolean isJobReadPermission(Permission permission) {
        if (permission.owner.equals(hudson.model.Item.class) && permission.name.equals('Read')) {
            return true
        }
        return false
    }
    boolean isDevPermission(Permission permission) {
        if (permission.equals(Jenkins.READ)) {
            return true
        }
        if (permission.owner.equals(com.cloudbees.plugins.credentials.CredentialsProvider.class) && permission.name.equals('View')) {
            return true
        }
        if (permission.owner.equals(hudson.model.Item.class)) {
            return true
        }
        if (permission.owner.equals(hudson.model.Run.class)) {
            return true
        }
        if (permission.owner.equals(hudson.model.View.class)) {
            return true
        }
        if (permission.owner.equals(hudson.scm.SCM.class)) {
            return true
        }
        if (permission.owner.equals(hudson.security.Permission.class)) {
            return true
        }
        if (permission.owner.equals(org.jfrog.hudson.ArtifactoryPlugin.class)) {
            return true
        }
        return false
    }
    void setPermissions(Map<Permission, Set<String>> permissions, AuthorizationStrategy ast) throws Throwable{
        def gst = new GlobalMatrixAuthorizationStrategy()
        if (ast instanceof ProjectMatrixAuthorizationStrategy) {
            gst = new ProjectMatrixAuthorizationStrategy()
        }
        for (Permission key : permissions.keySet()) {
            Set<String> val = permissions.get(key)
            for (String v : val) {
                if (v != null && v.trim().length() > 0) {
                    gst.add(key, v)
                }
            }
        }
        Jenkins.getInstance().setAuthorizationStrategy(gst)
        Jenkins.getInstance().save()
    }

    //############################################Github org folder config############################################
    void addOrUpdateGithubOrgFolder(String gitOrg, String credId, String gitUser, String gitPwd, String apiUrl, String gitRepos, String branches) throws Throwable{
        if (isEmpty(gitOrg)) {
            throw new Throwable('[addGithubOrgFolder] gitOrg is empty')
        }
        if (isEmpty(credId)) {
            throw new Throwable('[addGithubOrgFolder] credId is empty')
        }
        if (isEmpty(gitUser)) {
            throw new Throwable('[addGithubOrgFolder] gitUser is empty')
        }

        if (isEmpty(gitPwd)) {
            throw new Throwable('[addGithubOrgFolder] gitPwd is empty')
        }

        if (isEmpty(apiUrl)) {
            throw new Throwable('[addGithubOrgFolder] apiUrl is empty')
        }

        if (isEmpty(gitRepos)) {
            throw new Throwable('[addGithubOrgFolder] gitRepos is empty')
        }

        if (isEmpty(branches)) {
            throw new Throwable('[addGithubOrgFolder] branches is empty')
        }
        def spaceBranches = branches.replace('|', ' ')
        def jenkinsInstance = Jenkins.instance
        def env = System.getenv()

        def gitCreds = this.addOrUpdateStandardCredential(credId, gitUser, gitPwd)

        def jobConfigXml = """
               <jenkins.branch.OrganizationFolder plugin="[email protected]">
              <actions>
                <io.jenkins.blueocean.service.embedded.BlueOceanUrlAction plugin="[email protected]">
                  <blueOceanUrlObject class="io.jenkins.blueocean.service.embedded.BlueOceanUrlObjectImpl">
                    <mappedUrl>blue/organizations/jenkins/pipelines/</mappedUrl>
                  </blueOceanUrlObject>
                </io.jenkins.blueocean.service.embedded.BlueOceanUrlAction>
              </actions>
              <description>$gitOrg</description>
              <displayName>$gitOrg</displayName>
              <properties>
                <org.jenkinsci.plugins.pipeline.modeldefinition.config.FolderConfig plugin="[email protected]">
                  <dockerLabel></dockerLabel>
                  <registry plugin="[email protected]"/>
                </org.jenkinsci.plugins.pipeline.modeldefinition.config.FolderConfig>
                <jenkins.branch.NoTriggerOrganizationFolderProperty>
                  <branches>$branches</branches>
                </jenkins.branch.NoTriggerOrganizationFolderProperty>
              </properties>
              <folderViews class="jenkins.branch.OrganizationFolderViewHolder">
                <owner reference="../.."/>
              </folderViews>
              <healthMetrics>
                <com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric plugin="[email protected]">
                  <nonRecursive>false</nonRecursive>
                </com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric>
              </healthMetrics>
              <icon class="jenkins.branch.MetadataActionFolderIcon">
                <owner class="jenkins.branch.OrganizationFolder" reference="../.."/>
              </icon>
              <orphanedItemStrategy class="com.cloudbees.hudson.plugins.folder.computed.DefaultOrphanedItemStrategy" plugin="[email protected]">
                <pruneDeadBranches>true</pruneDeadBranches>
                <daysToKeep>5</daysToKeep>
                <numToKeep>5</numToKeep>
              </orphanedItemStrategy>
              <triggers>
                <com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger plugin="[email protected]">
                  <spec>* * * * *</spec>
                  <interval>86400000</interval>
                </com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger>
              </triggers>
              <disabled>false</disabled>
              <navigators>
                <org.jenkinsci.plugins.github__branch__source.GitHubSCMNavigator plugin="[email protected]">
                  <repoOwner>$gitOrg</repoOwner>
                  <apiUri>$apiUrl</apiUri>
                  <credentialsId>$credId</credentialsId>
                  <traits>
                    <jenkins.scm.impl.trait.RegexSCMSourceFilterTrait plugin="[email protected]">
                      <regex>$gitRepos</regex>
                    </jenkins.scm.impl.trait.RegexSCMSourceFilterTrait>
                    <org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait>
                      <strategyId>3</strategyId>
                    </org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait>
                    <org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait>
                      <strategyId>2</strategyId>
                    </org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait>
                    <org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait>
                      <strategyId>2</strategyId>
                    </org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait>
                    <jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait plugin="[email protected]">
                      <includes>$spaceBranches</includes>
                      <excludes></excludes>
                    </jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait>
                  </traits>
                </org.jenkinsci.plugins.github__branch__source.GitHubSCMNavigator>
              </navigators>
              <projectFactories>
                <org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory plugin="[email protected]">
                  <scriptPath>cicada/.cicada</scriptPath>
                </org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory>
                <org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory plugin="[email protected]">
                  <scriptPath>Jenkinsfile</scriptPath>
                </org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory>
              </projectFactories>
            </jenkins.branch.OrganizationFolder>
            """

        def job = jenkinsInstance.createProjectFromXML(gitOrg, new ByteArrayInputStream(jobConfigXml.getBytes('UTF-8')))

        job.save()
        //the following will actually kickoff the initial scanning
        ACL.impersonate(ACL.SYSTEM, new Runnable() {

            @Override public void run() {
                for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
                    if (owner instanceof OrganizationFolder) {
                        OrganizationFolder orgFolder = (OrganizationFolder) owner
                        for (GitHubSCMNavigator navigator : orgFolder.getNavigators().getAll(GitHubSCMNavigator.class)) {
                            orgFolder.scheduleBuild()
                        }
                    }
                }
            }

        })
    }

    
    //############################################Github oauth config config############################################
    void enableGithubAuthMatrixAuthz(String gitWebUrl, String gitApiUrl, String clientId, String clientSecret, String oauthScopes, String adminIds, String developerIds, String viewerIds, String orgName) throws Throwable{
        if (isEmpty(gitWebUrl)) {
            throw new Throwable('[enableGithubOauth] gitWebUrl is empty')
        }
        if (isEmpty(gitApiUrl)) {
            throw new Throwable('[enableGithubOauth] gitApiUrl is empty')
        }
        if (isEmpty(clientId)) {
            throw new Throwable('[enableGithubOauth] clientId is empty')
        }
        if (isEmpty(clientSecret)) {
            throw new Throwable('[enableGithubOauth] clientSecret is empty')
        }
        if (isEmpty(oauthScopes)) {
            throw new Throwable('[enableGithubOauth] oauthScopes is empty')
        }
        SecurityRealm githubOauth = new GithubSecurityRealm(gitWebUrl, gitApiUrl, clientId, clientSecret, oauthScopes)
        AuthorizationStrategy ast = new GlobalMatrixAuthorizationStrategy()
        ast.add(Jenkins.ADMINISTER, 'propel-support*' + getWsId() + '-admin')
        if (!isEmpty(orgName)) {
            ast.add(Jenkins.READ, orgName)
            for (PermissionGroup pg : PermissionGroup.getAll()) {
                for (Permission p : pg.getPermissions()) {
                    if (isJobReadPermission(p)) {
                        ast.add(p, orgName)
                    }
                }
            }
        }
        Jenkins.instance.setSecurityRealm(githubOauth)
        Jenkins.instance.setAuthorizationStrategy(ast)
        Jenkins.instance.save()

        this.configureDevOpsAdmin(adminIds, '')
        this.configureDeveloper(developerIds, '')
        this.configureViewer(viewerIds, '')
    }

    void migrateToMatrixAuthz(String adminIds, String developerIds, String viewerIds) {
        AuthorizationStrategy ast = Jenkins.getInstance().getAuthorizationStrategy()
        if (! (ast instanceof GlobalMatrixAuthorizationStrategy)) {
            ast = new GlobalMatrixAuthorizationStrategy()
        }
        ast.add(Jenkins.ADMINISTER, 'propel-support*' + getWsId() + '-admin')
        ast.add(Jenkins.READ, 'authenticated')
        Jenkins.instance.setAuthorizationStrategy(ast)
        Jenkins.instance.save()
        this.configureDevOpsAdmin(adminIds, '')
        this.configureDeveloper(developerIds, '')
        this.configureViewer(viewerIds, '')
    }

    void reloadJenkins() {
        def jenkinsInstance = Jenkins.instance
        jenkinsInstance.doReload()
    }

//###################### Kubernetes Plugin Config ##############################

    def instance = Jenkins.getInstance()

    void configureKubernetes() {
        println (instance.pluginManager.activePlugins.find { it.shortName == 'kubernetes' } )
        println 'JENKINS_KUBERNETES_AUTOCONF'

        if ((instance.pluginManager.activePlugins.find { it.shortName == 'kubernetes' } != null )) {
            println '[kubernetes.groovy] Kubernetes plugin autoconfiguration enabled'

            def cloudList = instance.clouds

            def kubernetesClouds = []
            def kubernetesFlag = false

            for (String it : cloudList) {
                if (it.toString().contains('KubernetesCloud')) {
                    println '[kubernetes.groovy] Found Kubernetes Cloud Configuration'
                    kubernetesClouds.add(cloudList.getByName('kubernetes'))
                    kubernetesFlag = true
                }
            }

            println 'kubernetes configuration exist::' + kubernetesFlag

            if (kubernetesFlag) {
                kubernetesClouds.each {
                    setKubernetesCloud(it, metaDataMap)
                }
            } else {
                addKubernetesCloud(cloudList, metaDataMap)
            }
    }
}

    def addKubernetesCloud(cloudList, env) {
        println '[kubernetes.groovy]  No pre-existing Kubernetes Cloud configuration found. Adding new config.'

        def mergeYaml = '''\
apiVersion: v1
kind: Pod
spec:
 automountServiceAccountToken: false
 tolerations:
 -  key: "node.kubernetes.io/unreachable"
    operator: "Exists"
    effect: "NoExecute"
    tolerationSeconds: 30
 -  key: "type"
    operator: "Equal"
    value: "build"
    effect: "NoSchedule"
'''

        def cloud = new KubernetesCloud(
                        env['JENKINS_KUBERNETES_NAME'] ?: 'kubernetes',
        )

        def numTemplates = []

        env.keySet().grep(~/JENKINS_KUBERNETES_([0-9]{1,3})_.*/).each {
                def matcher = it =~ '[0-9]{1,3}'
                numTemplates.add(matcher[0])
    }

        for (i in numTemplates.unique().sort()) {
            def mode_e = Node.Mode.EXCLUSIVE
            def p = new PodTemplate()
            p.setName(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_NAME"] ?: '')
            p.setNamespace(getWsId())
            p.setLabel(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_LABELS"] ?: '')
            p.setNodeUsageMode(mode_e)
            p.setIdleMinutes(1)
            p.setRemoteFs(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_REMOTE_FS"] ?: '')
            p.setSlaveConnectTimeout(100)
            p.setRunAsUser(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_RUN_AS_USERID"] ?: '')
            p.setRunAsGroup(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_RUN_AS_GROUPID"] ?: '')
            p.setNodeSelector(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_NODE_SELECTOR"] ?: 'type=build')
            p.setServiceAccount(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_SERVICE_ACCOUNT"] ?: '')
            p.setYaml(mergeYaml)
            p.setShowRawYaml(false)

            def numContainers = []

            env.keySet().grep(~/JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_[0-9]{1,3}_.*/).sort().each {
                def matcher = it =~ '[0-9]{1,3}'
                numContainers.add(matcher[0])
        }

            //add containerTemplate
            def containers = new ArrayList<>()

            for (k in numContainers.unique().sort()) {
                def containerTemplate = new ContainerTemplate('jnlp')

                containerTemplate.setName(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_NAME"] ?: 'jnlp')
                containerTemplate.setImage(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_DOCK_IMG"] ?: '')
                containerTemplate.setAlwaysPullImage((env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_ALWAYS_PULL_IMAGE"] ?: 'false').toBoolean())
                containerTemplate.setWorkingDir(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_WORKING_DIRECTORY"] ?: '/home/jenkins/agent')
                containerTemplate.setCommand(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_COMMANDS_TO_RUN"] ?: '/usr/local/bin/wrapper.sh')
                containerTemplate.setArgs(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_SET_ARGS"] ?: '')
                containerTemplate.setTtyEnabled((env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_ALLOCATE_PSEUDO_TTY"] ?: 'true').toBoolean())
                containerTemplate.setPrivileged((env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_SET_PRIVILEGE_MODE"] ?: 'true').toBoolean())
                containerTemplate.setRunAsUser(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_RUN_AS_USERID"] ?: '')
                containerTemplate.setRunAsGroup(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_RUN_AS_GROUPID"] ?: '')
                containerTemplate.setResourceRequestCpu(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_REQUEST_CPU"] ?: '')
                containerTemplate.setResourceRequestMemory(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_REQUEST_MEMORY"] ?: '')
                containerTemplate.setResourceLimitCpu(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_LIMIT_CPU"] ?: '')
                containerTemplate.setResourceLimitMemory(env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_CONTAINER_${k}_LIMIT_MEMORY"] ?: '')

                containers.add(containerTemplate)
            }

            if (!containers.isEmpty()) {
                p.setContainers(containers)
            }

            List<TemplateEnvVar> envVars = new ArrayList<TemplateEnvVar>()

            env.keySet().grep(~/JENKINS_KUBERNETES_${i}_POD_TEMPLATE_ENVVARS_[0-9]{1,3}/).sort().each {
                    def envVar = env["${it}"].trim() =~ /(.*)::(.*)/
                    if (envVar.matches()) {
                    def templateEnvVar = new KeyValueEnvVar(
                                envVar[0][1],
                                envVar[0][2]
                            )
                    envVars.add(templateEnvVar)
                    } else {
                    println "[kubernetes.groovy]  error adding env vars: ${it} -- ${env[it]}"
                    }
            }

            if (!envVars.isEmpty()) {
                p.setEnvVars(envVars)
            }

            //add imagePullSecrets
            List<PodImagePullSecret> imagePullSecrets = new ArrayList<PodImagePullSecret>()

            env.keySet().grep(~/JENKINS_KUBERNETES_${i}_POD_TEMPLATE_IMAGE_PULL_SECRETS_[0-9]{1,3}/).sort().each {
                def pullSecret = env["${it}"].trim() =~ /(.*)/
                if (pullSecret.matches()) {
                    def podImagePullSecret = new PodImagePullSecret(
                            pullSecret[0][1]
                    )
                    imagePullSecrets.add(podImagePullSecret)
                } else {
                    println "[kubernetes.groovy]  error processing pull secret: ${it} -- ${env[it]}"
                }
            }

            if (!imagePullSecrets.isEmpty()) {
                p.setImagePullSecrets(imagePullSecrets)
            }

            //add annotations
            if (env['WINDOWS_EC2_FLAG'] == 'true') {
                List<PodAnnotation> annotations = new ArrayList<PodAnnotation>()

                env.keySet().grep(~/JENKINS_KUBERNETES_${i}_POD_TEMPLATE_ANNOTATION_[0-9]{1,3}/).sort().each {
                    def annotation = env["${it}"].trim() =~ /(.*)::(.*)/
                    if (annotation.matches()) {
                        def podAnnotation = new PodAnnotation(
                                annotation[0][1],
                                annotation[0][2]
                            )
                        annotations.add(podAnnotation)
                    } else {
                        println "[kubernetes.groovy]  error adding annotations: ${it} -- ${env[it]}"
                    }
            }

                if (!annotations.isEmpty()) {
                    p.setAnnotations(annotations)
                }
            }

            cloud.addTemplate(p)
        }

        cloud.setNamespace(getWsId())
        cloud.setJenkinsUrl(env['JENKINS_KUBERNETES_URL'] ?: '')
        cloud.setConnectTimeout(5)
        cloud.setReadTimeout(15)
        cloud.setWaitForPodSec(600)
        cloud.setMaxRequestsPerHostStr('32') //max connections to kubernetes API
        cloud.setContainerCapStr(env['JENKINS_KUBERNETES_CONCURRENCY_LIMIT'] ?: '2') //concurrency limit
        cloud.setSkipTlsVerify(false) //disable https certificate check
        cloud.setDefaultsProviderTemplate(env['JENKINS_KUBERNETES_DEFAULT_PROVIDER_TEMPLATE'] ?: 'propel')

        cloudList.add(cloud)
    }

    def setKubernetesCloud(cloud, env) {
        println '[kubernetes.groovy]  Kubernetes Cloud already defined. Updating Configuration.'
        for (int j = 0; j < cloud.getTemplates().size(); j++) {
            if ((cloud.getTemplates() == null) || (cloud.getTemplates().get(j).name == 'k8s-dind-large')) {
                continue
            }

            def p = new PodTemplate()
            p.setName(cloud.getTemplates().get(j).name)
            p.setNamespace(cloud.getTemplates().get(j).namespace)
            p.setRunAsUser(cloud.getTemplates().get(j).runAsUser)
            p.setRunAsGroup(cloud.getTemplates().get(j).runAsGroup)
            p.setLabel(cloud.getTemplates().get(j).label)
            p.setNodeUsageMode(cloud.getTemplates().get(j).nodeUsageMode)
            p.setWorkspaceVolume(cloud.getTemplates().get(j).workspaceVolume)
            p.setImagePullSecrets(cloud.getTemplates().get(j).imagePullSecrets)
            p.setNodeSelector(cloud.getTemplates().get(j).nodeSelector)
            p.setServiceAccount(cloud.getTemplates().get(j).serviceAccount)
            p.setYaml(cloud.getTemplates().get(j).yamls)
            p.setShowRawYaml(false)
            p.setEnvVars(cloud.getTemplates().get(j).envVars)

            //update containerTemplate
            def containers = new ArrayList<>()

            for (int k = 0; k < cloud.getTemplates().containers.get(j).size(); k++) {
                def name = cloud.getTemplates().containers.get(j).get(k).getName()

                def container = new ContainerTemplate(name)

                container.setName(cloud.getTemplates().containers.get(j).get(k).getName())
                container.setImage(cloud.getTemplates().containers.get(j).get(k).getImage())
                container.setPrivileged(cloud.getTemplates().containers.get(j).get(k).isPrivileged())
                container.setRunAsUser(cloud.getTemplates().containers.get(j).get(k).getRunAsUser())
                container.setRunAsGroup(cloud.getTemplates().containers.get(j).get(k).getRunAsGroup())
                container.setAlwaysPullImage(cloud.getTemplates().containers.get(j).get(k).isAlwaysPullImage())
                container.setWorkingDir(cloud.getTemplates().containers.get(j).get(k).getWorkingDir())
                container.setCommand(cloud.getTemplates().containers.get(j).get(k).getCommand())
                container.setArgs(cloud.getTemplates().containers.get(j).get(k).getArgs())
                container.setTtyEnabled(cloud.getTemplates().containers.get(j).get(k).isTtyEnabled())
                container.setResourceRequestCpu(cloud.getTemplates().containers.get(j).get(k).getResourceRequestCpu())
                if (env['REQUEST_MEMORY']) {
                    println 'Using REQUEST_MEMORY'
                    container.setResourceRequestMemory(env['REQUEST_MEMORY'])
                } else {
                    println 'Using existing value'
                    println cloud.getTemplates().containers.get(j).get(k).getResourceRequestMemory()
                    container.setResourceRequestMemory(cloud.getTemplates().containers.get(j).get(k).getResourceRequestMemory())
                }    
                container.setResourceLimitCpu(cloud.getTemplates().containers.get(j).get(k).getResourceLimitCpu())
                if (env['LIMIT_MEMORY']) {
                    container.setResourceLimitMemory(env['LIMIT_MEMORY'])
                } else {
                    container.setResourceLimitMemory(cloud.getTemplates().containers.get(j).get(k).getResourceLimitMemory())
                } 
                container.setShell(cloud.getTemplates().containers.get(j).get(k).getShell())
                container.setEnvVars(cloud.getTemplates().containers.get(j).get(k).getEnvVars())
                container.setPorts(cloud.getTemplates().containers.get(j).get(k).getPorts())
                container.setLivenessProbe(cloud.getTemplates().containers.get(j).get(k).getLivenessProbe())

                containers.add(container)
            }

            if (!containers.isEmpty()) {
                p.setContainers(containers)
            }

            //add annotations
            if (env['WINDOWS_EC2_FLAG'] == 'true') {
                def numTemplates = []

                env.keySet().grep(~/JENKINS_KUBERNETES_([0-9]{1,3})_.*/).each {
                    def matcher = it =~ '[0-9]{1,3}'
                    numTemplates.add(matcher[0])
            }

                List<PodAnnotation> annotations = new ArrayList<PodAnnotation>()

                for (i in numTemplates.unique().sort()) {
                    if (env["JENKINS_KUBERNETES_${i}_POD_TEMPLATE_NAME"] == cloud.getTemplates().get(j).name) {
                        env.keySet().grep(~/JENKINS_KUBERNETES_${i}_POD_TEMPLATE_ANNOTATION_[0-9]{1,3}/).sort().each {
                            def annotation = env["${it}"].trim() =~ /(.*)::(.*)/
                            if (annotation.matches()) {
                                def podAnnotation = new PodAnnotation(
                                        annotation[0][1],
                                        annotation[0][2]
                                    )
                                annotations.add(podAnnotation)
                            } else {
                                println "[kubernetes.groovy]  error updating annotations: ${it} -- ${env[it]}"
                            }
                    }
                }
        }

                if (!annotations.isEmpty()) {
                    p.setAnnotations(annotations)
                }
    }

            cloud.getTemplates().set(j, p)
        }
        cloud.setContainerCapStr(env['JENKINS_KUBERNETES_CONCURRENCY_LIMIT'])
    }

    void configureKubernetesDockerCacheVolume() {
            def instance = Jenkins.getInstance()
            def cloudList = instance.clouds

            def kubernetesClouds = []
            def kubernetesFlag = false

            for (String it : cloudList) {
                if (it.toString().contains('KubernetesCloud')) {
                    println '[kubernetes.groovy] Found Kubernetes Cloud Configuration'
                    kubernetesClouds.add(cloudList.getByName('kubernetes'))
                    kubernetesFlag = true
                }
            }

            println 'kubernetes configuration exist::' + kubernetesFlag

            def dindLabel = Jenkins.instance.getLabel("dind")
            if (kubernetesFlag) {
                kubernetesClouds.each {
                    def podTemplate = it.getTemplate(dindLabel)
                    def volumes = []
                    def hostPath = "/kubernetes/volume0/" + getWsId()
                    volumes << new HostPathVolume(hostPath, "/opt/docker-cache")
                    podTemplate.setVolumes(volumes)
                }
            }
            instance.save()
    }    

//##################################### End Kubernetes plugin Config #####################################

    //############################################EC2 Plugin config new function############################################
    void configureEC2(String windowsFlag) {
        def slurper = new JsonSlurper()
        def result = slurper.parseText(metaDataDefault)
        def instance = Jenkins.getInstance()

        if ((instance.pluginManager.activePlugins.find { it.shortName == 'ec2' } != null )) {
            logger.info('in ec2 config')
            def cloudList = instance.clouds

            if (windowsFlag == 'true' && result.amis.size() != 0) {
                logger.info('removing ec2 config')
                cloudList.remove(cloudList.getByName('ec2-windows'))
                logger.info('creating ec2 credential')
                addOrUpdateEC2SSHCredential()
                logger.info('creating ec2 config')
                addEC2Cloud(cloudList, result)
            } else {
                logger.info('remove ec2 config')
                cloudList.remove(cloudList.getByName('ec2-windows'))
                logger.info('remove ec2 credential')
                removeSSHCredential()
            }
    }
        instance.save()
    }

    def addEC2Cloud(cloudList, result) {
        def i = 0
        List<SlaveTemplate> amiList = new ArrayList<SlaveTemplate>()

        for (i = 0; i < result.amis.size(); i++) {
            logger.info(' Adding AMI Slave config.')

            def instType = InstanceType.fromValue(result.amis[i].size ?: '')

            def tags = [
                    // TODO: change or delete this Name=12345 ???
                    new EC2Tag('Name', getWsId()),
                    new EC2Tag('Env', 'Production'),
                    new EC2Tag('App', 'propel-windows'),
                    new EC2Tag('Contact', '[email protected]'),
                    new EC2Tag('Org', 'build.ge'),
                    new EC2Tag('uai', 'UAI3037833'),
                    new EC2Tag('Team', 'propel'),
                    new EC2Tag('Owner', '[email protected]')
                ]

            logger.info('timeout:' + result.amis[i].timeout)

            def String timeout
            if (result.amis[i].timeout == null) {
                timeout = '1'
        } else {
                timeout = Integer.toString(result.amis[i].timeout)
            }

            def worker_ami = new SlaveTemplate(
                    result.amis[i].id ?: '',
                    result.amis[i].availabilityZone ?: '',
                    null,
                    result.amis[i].securityGroup ?: '',
                    'c:/',
                    instType,
                    false,
                    result.amis[i].labels ?: '',
                    Node.Mode.EXCLUSIVE,
                    result.amis[i].name ?: '',
                    '',
                    '',
                    '',
                    '1',
                    'Administrator',
                    new WindowsData(result.amis[i].password ?: '', false, '', true),
                    '',
                    false,
                    result.amis[i].subnetID ?: '',
                    tags,
                    timeout,
                    '',
                    result.amis[i].instanceProfile ?: '',
                    true,
                    false,
                    false,
                    '1800',
                    false,
                    '',
                    false,
                    false,
                    false,
                    hudson.plugins.ec2.ConnectionStrategy.PRIVATE_IP,
                    -1
        )
            amiList.add(worker_ami)
        }


        def new_cloud = new AmazonEC2Cloud(
                        result.cloudName,
                        true,
                        '',
                        result.region ?: '',
                        '',
                        'EC2Key',
                        '5',
                        amiList,
                        '',
                        ''
                    )
        cloudList.add(new_cloud)
        logger.info('Added EC2 Configuration')
    }

    //############################################System abstract methods. Do not touch############################################
    abstract String getTxId();
    abstract String getWsId();
    abstract String getSSO();
    abstract String getInstanceId();
    abstract String getFunctionName();
    abstract void init();

    boolean isEmpty(String s) {
        if (s == null) {
            return true
        }
        if (s.trim().length() == 0) {
            return true
        }
        return false
    }
    public addMetaData(String key, String val) {
        if (key.endsWith('_SECRET')) {
            val = '********'
        }
        if (this.metaData.length() == 0) {
            this.metaData = key + '=' + val
        }else {
            this.metaData += ',' + key + '=' + val
        }
    }
    public String getMetaData() {
        return metaData
    }

    public addMetaDataMap(String s) {
        String[] entrys = s.split("\\|")
        for (String entry:entrys) {
            String[] kv = entry.split('#')
            this.metaDataMap.put(kv[0], kv[1])
        }
    }
    public getMetaDataMap() {
        return metaDataMap
    }

    public addMetaDataDefault(String s) {
        this.metaDataDefault = s
    }
    public getMetaDataDefault() {
        return metaDataDefault
    }

    //############################################Configure GovCloud disable users rols edit############################################
    void disableEditFromInstance(String govCloud, String mesosDisableCssUrl, String mesosDisableJsUrl, String userDisableJsUrl) throws Throwable{
        if (isEmpty(mesosDisableCssUrl)) {
            throw new Throwable('[addJavaScriptToSimpleTheme] mesosDisableCssUrl is empty')
        }

        if (isEmpty(mesosDisableJsUrl)) {
            throw new Throwable('[addJavaScriptToSimpleTheme] mesosDisableJsUrl is empty')
        }

        if (govCloud == 'true') {
            if (isEmpty(userDisableJsUrl)) {
                throw new Throwable('[addJavaScriptToSimpleTheme] userDisableJsUrl is empty')
            }
        }

        def instance = Jenkins.getInstance()

        def themeDecorator = instance.getExtensionList(org.codefirst.SimpleThemeDecorator.class).first()

        if (govCloud == 'true') {
            themeDecorator.setElements([new CssUrlThemeElement(mesosDisableCssUrl), new JsUrlThemeElement(mesosDisableJsUrl), new JsUrlThemeElement(userDisableJsUrl)])
        } else {
            themeDecorator.setElements([new CssUrlThemeElement(mesosDisableCssUrl), new JsUrlThemeElement(mesosDisableJsUrl)])
        }

        themeDecorator.save()
        instance.save()
    }

    //############################################Remove ec2 windows plugin configuration############################################
    void removeEc2ConfigFromInstance(String removeEc2Config) throws Throwable{
        println 'removing ec2 config:' + removeEc2Config

        if (isEmpty(removeEc2Config)) {
            throw new Throwable('removeEc2Config is empty')
        }

        if (removeEc2Config == 'true') {
            def instance = Jenkins.instance
            def cloudList = instance.clouds

            if (cloudList.getByName('ec2-windows')) {
                cloudList.remove(cloudList.getByName('ec2-windows'))
            }
            instance.save()
        }
    }

//############################################SendMetrics Function for jenkins############################################

void sendMetrics(String nodeName, String workspaceID, String memory) {
    Connection conn = null;

    try {
        def scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        String privatePemDir = scriptDir + "/" + "privatekey-pkcs8.pem"
        PrivateKey privateKey = loadPrivateKey(privatePemDir);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        String rmqHost = getEncryptedValueFromEnv("RMQ_HOST", cipher)
        String rmqPort = getFromEnv("RMQ_PORT")
        String rmqUser = getEncryptedValueFromEnv("RMQ_USER", cipher)
        String rmqPwd = getEncryptedValueFromEnv("RMQ_PWD", cipher)

        conn = openConnection(rmqHost, rmqPort, rmqUser, rmqPwd)

        println("\n**********  BuildMetrics - processing metrics for node: ${nodeName} **********");

        nodeDetails = mapByNodeName.get(nodeName);
        def currentTime = new Date()
        def nodeStartTime = new Date(nodeDetails.startDate.getTime())

        def metrics = [
            File: "build_metrics.go",
            Function: "main.postBuildMetrics",
            LineNum: 94,
            level: "debug",
            msg: "creating/updating elastic document metadata{" +
                   "\"metricID\":\"${workspaceID}\"," +
                   "\"workspaceID\":\"${workspaceID}\"," +
                   "\"instanceID\":\"${nodeName}\"," +
                   "\"os\":\"Linux, 3.10.0-1160.95.1.el7.x86_64, amd64/64\"," +
                   "\"startTime\":\"${nodeStartTime.format("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX", TimeZone.getTimeZone('UTC'))}\"," +
                   "\"timeStamp\":\"${currentTime.format("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX", TimeZone.getTimeZone('UTC'))}\"," +
                   "\"buildNumber\":${nodeDetails.buildNumber}," +
                   "\"buildName\":\"${nodeDetails.buildName}\"," +
                   "\"usedMemoryMB\":${memory}," +
                   "\"buildDuration\":${currentTime.getTime() - nodeStartTime.getTime()}," +
                   "\"concurrentBuilds\":${runningExecutors}" +
                   "}",
            time: currentTime.format("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'", TimeZone.getTimeZone('UTC'))
        ]

        println(metrics)

        // You can add more logic here based on your requirements

    } catch (Throwable th) {
        // Your existing error handling code
    } finally {
        if (conn != null) {
            conn.close()
        }
    }
    
}
} 

Groovy online compiler

Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.

Read inputs from stdin

OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.

def name = System.in.newReader().readLine()
println "Hello " + name

About Groovy

Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.

Key Features

  • It's not a replacement for java but it's an enhancer to Java with extra features like DSL support, dynamic typing, closures etc.
  • Accepts Java code as it extends JDK
  • Greater flexibility
  • Concise and much simpler compared to Java
  • Can be used as both programming language and scripting language.

Syntax help

Data Types

Data typeDescriptionRange
StringTo represent text literalsNA
charTo represent single character literalNA
intTo represent whole numbers-2,147,483,648 to 2,147,483,647
shortTo represent short numbers-32,768 to 32,767
longTo represent long numbers-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
doubleTo represent 64 bit floating point numbers4.94065645841246544e-324d to 1.79769313486231570e+308d
floatTo represent 32 bit floating point numbers1.40129846432481707e-45 to 3.40282346638528860e+38
byteTo represent byte value-128 to 127
booleanTo represent boolean values either true or falseTrue or False

Variables

You can define variables in two ways

Syntax:

data-type variable-name;

[or]

def variable-name;

Loops

0.upto(n) {println "$it"}

or

n.times{println "$it"}

where n is the number of loops and 0 specifies the starting index

Decision-Making

1. If / Nested-If / If-Else:

When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

List

List allows you to store ordered collection of data values.

Example:

def mylist = [1,2,3,4,5];
List MethodsDescription
size()To find size of elements
sort()To sort the elements
add()To append new value at the end
contains()Returns true if this List contains requested value.
get()Returns the element of the list at the definite position
pop()To remove the last item from the List
isEmpty()Returns true if List contains no elements
minus()This allows you to exclude few specified elements from the elements of the original
plus()This allows you to add few specified elements to the elements of the original
remove()To remove the element present at the specific position
reverse()To reverse the elements of the original List and creates new list