DEV Community

Query Filter
Query Filter

Posted on

gradle-76

// ==============================================================================
// 1. IMPORTS
// NEW / MODIFIED: Added imports required for TAR creation, JSON output, and MANIFEST processing.
// ==============================================================================
import groovy.json.JsonOutput
import java.text.SimpleDateFormat
import java.util.concurrent.atomic.AtomicBoolean
import java.util.jar.Manifest

// ==============================================================================
// 2. PLUGINS
// NEW / MODIFIED: Cleaned up plugins list. Removed 'nebula.ospackage' (RPM plugin)
// and removed 'apply from: build-rpm.gradle' reference from the script.
// ==============================================================================
plugins { 
    id 'idea' 
    id 'java' 
    id 'org.springframework.boot' version '2.6.4' 
    id 'com.citi.171981.java-convention' 
    id 'application' 
    id 'distribution' 
    id 'com.citi.161668.fxdevops.gradle-plugins.blackduck-plugin' 
}

blackDuckScan { 
    failOnIssue = true 
    failOnSeverity = 'HIGH' 
    includeBuildDependencies = false 
    includeTestDependencies = false 
    printAsTree = false 
    printOnlySummary = true 
    whiteListUrl = 'https://blackduck-whitelist-service.apps.namicg39837p.ecs.dyn.nsroot.net/whitelist' 
}

// Disable ZIP and BootJar distribution tasks in favor of custom TAR packaging
tasks.distZip.enabled = false 
bootDistZip { enabled = false } 
bootJar { enabled = false } 

// ==============================================================================
// 3. DYNAMIC VERSION RESOLUTION & PARSING
// NEW / MODIFIED: Updated string stripping to target 'rio-collector.' instead of 'gcomet.'.
// Retained multi-part branch versioning logic from the base build script.
// ==============================================================================
println "project version before modifying -> '${version}'"
def versionParts = version.toString().split('-', 3)

// Example 1 (Release branch): "1.0.0-a1b2c3d-rio-collector.release.v1"
//   versionParts[0] = "1.0.0"
//   versionParts[1] = "a1b2c3d"
//   versionParts[2] = "rio-collector.release.v1"
//
// Example 2 (Feature branch): "1.0.0-f8e9d7c-rio-collector.feature-branch"
//   versionParts[0] = "1.0.0"
//   versionParts[1] = "f8e9d7c"
//   versionParts[2] = "rio-collector.feature-branch"

project.ext {
    // Extracts "1.0.0"
    minorBuildVersion = versionParts.length > 0 ? versionParts[0] : 0

    // Extracts "a1b2c3d" or "f8e9d7c" (Git commit hash)
    gitCommitId = versionParts.length > 1 ? versionParts[1] : 'unknown'

    // Strips "rio-collector." and "release." prefixes
    // Example 1 transforms "rio-collector.release.v1" -> "v1"
    // Example 2 transforms "rio-collector.feature-branch" -> "feature-branch"
    versionSuffix = (versionParts.length > 2 ? versionParts[2] : 'unknown')
                        .replaceAll('([^a-zA-Z0-9_.-])', '')
                        .replaceAll('release\\.', '')
                        .replaceAll('rio-collector\\.', '')

    // Sets versionBuildNumber to "1.0.0"
    versionBuildNumber = "${minorBuildVersion}"
}

def isRelease = (versionParts.length > 2 && versionParts[2].contains('release'))
if (isRelease) {
    versionBuildNumber = "${minorBuildVersion}"
    version = "${versionSuffix}"
} else {
    versionBuildNumber = "${minorBuildVersion}"
    version = "${gitCommitId}"
}

println "project version after modifying -> '${version}'"
println "jar version -> '${jar.getArchiveVersion().get()}'"

// Set distribution archive base name
distribution {
    main {
        distributionBaseName = project.name
    }
}

// ==============================================================================
// 4. MANIFEST & TAR HELPER FUNCTIONS
// NEW / MODIFIED: Helper methods to generate external manifest.json and evaluate TAR build.
// ==============================================================================
String manifestFileName = 'manifest.json'

def generateManifest(String archivePath) {
    File f = new File(archivePath)
    def manifestPath = "${f.parent}/${manifestFileName}"
    def manifest = [tar_name: f.name]
    def manifestFile = new File(manifestPath)
    manifestFile.text = JsonOutput.prettyPrint(JsonOutput.toJson(manifest))
    println "Manifest is generated in: ${manifestPath}"
}

static boolean enableTarBuild(Project project) {
    if (project.hasProperty('enableTar')) {
        return Boolean.parseBoolean(project.property('enableTar').toString())
    }
    String pushPackage = System.getenv('PUSH_PACKAGE')
    if (pushPackage != null) {
        return "yes".equalsIgnoreCase(pushPackage) || "true".equalsIgnoreCase(pushPackage)
    }
    return true
}

// ==============================================================================
// 5. TAR PACKAGING & MANIFEST.MF TASKS
// NEW / MODIFIED: Replaced legacy RPM build logic with native .tar.gz packaging.
// Configures task to create internal MANIFEST.MF under META-INF inside the TAR.
// ==============================================================================
tasks.register('generateTarManifest') {
    def manifestFile = layout.buildDirectory.file("tmp/tar-manifest/MANIFEST.MF")
    outputs.file(manifestFile)
    doLast {
        File file = manifestFile.get().asFile
        file.parentFile.mkdirs()
        Manifest manifest = new Manifest()
        def attributes = manifest.mainAttributes
        attributes.putValue('Manifest-Version', '1.0')
        attributes.putValue('Built-By', System.getProperty('user.name'))
        attributes.putValue('Implementation-Version', project.version.toString())
        attributes.putValue('Build-Date', new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date()))
        attributes.putValue('Build-Jdk', "${System.getProperty('java.version')} (${System.getProperty('java.vendor')})")
        attributes.putValue('Build-OS', "${System.getProperty('os.name')} (${System.getProperty('os.arch')})")
        file.withOutputStream { os -> manifest.write(os) }
    }
}

if (enableTarBuild(project)) {
    def manifestTask = tasks.named('generateTarManifest')
    def metaInfPath = "${project.name}-${project.version}/META-INF"
    def externalManifestGenerated = new AtomicBoolean(false)

    tasks.named('distTar', Tar) {
        enabled = true
        compression = Compression.GZIP
        archiveExtension = 'tar.gz'
        into(metaInfPath) {
            from manifestTask
        }
        doLast {
            if (externalManifestGenerated.compareAndSet(false, true)) {
                generateManifest(archiveFile.get().asFile.absolutePath)
            }
        }
    }
} else {
    tasks.distTar.enabled = false
}

// ==============================================================================
// 6. TOOLCHAIN, REPOSITORIES & DEPENDENCIES
// UNCHANGED: Preserved intact from base script.
// ==============================================================================
idea { 
    module { 
        downloadJavadoc = false 
        downloadSources = false 
    } 
}

repositories { 
    maven { 
        url 'https://www.artifactrepository.citigroup.net/artifactory/maven-dev' 
        credentials { 
            username citiEarUser 
            password citiEarPassword 
        } 
    } 
}

java { 
    toolchain { 
        languageVersion = JavaLanguageVersion.of(8) 
    } 
}

configurations { 
    all*.exclude module: 'spring-boot-starter-tomcat' 
    all*.exclude module: 'spring-boot-starter-undertow' 
    all*.exclude group: 'com.citi.158760.qpsCompatibleAPI', module: 'qpsCompatibleAPI' 
    all*.exclude group: 'com.gemstone.gemfire', module: 'gemfire' 
    all*.exclude group: 'log4j', module: 'log4j' 
    all*.exclude module: 'EccpressoFIPSJCA' 
    all*.exclude module: 'OESIntF' 
    all*.exclude module: 'bcprov-jdk16' 
    all*.exclude group: 'com.citi.158667.quantum3_5' 
    all*.exclude group: 'com.citi.159667.quantum4_8' 
    all*.exclude group: 'com.citi.150667.quantum3_7' 
    all*.exclude group: 'com.citi.150667.quantum3_12' 
    all*.exclude group: 'com.citigroup.158667' 
    all*.exclude group: 'org.codehaus.jackson' 
    all*.exclude group: 'org.jdom' 
    all*.exclude group: 'com.citi.xenv-legacy.TIBCOEMS', module: 'tibcrypt' 
    all*.exclude group: 'org.apache.velocity', module: 'velocity' 
    all*.exclude group: 'velocity', module: 'velocity' 
    all*.exclude group: 'qfix', module: 'qfix' 
    all*.exclude group: 'antlr', module: 'antlr' 
    all*.exclude group: 'com.ssmb.aee.util', module: 'aeeUtil' 
    all*.exclude group: 'com.tibco', module: 'jms-2.0' 
    all*.exclude group: 'javax.jms', module: 'jws-2.0' 
    all*.exclude group: 'javax.jms', module: 'jms' 
    all*.exclude group: 'jgroups' 
    all*.exclude group: 'com.citi.datainfra.dna.java_dependencies', module: 'jconn4' 
    all*.exclude group: 'com.sybase', module: 'jconn4' 
    all*.exclude group: 'com.citi.35503.acctapi', module: 'xercesImpl' 
    all*.exclude group: 'org.apache.logging.log4j', module: 'log4j-slf4j-impl' 
    all*.exclude group: 'com.citi.154402.refdata', module: 'slf4j-simple' 
    all*.exclude group: 'org.antlr', module: 'antlr' 
    all*.exclude group: 'org.antlr', module: 'antlr-runtime' 
    all*.exclude group: 'cyberark', module: 'javapasswordsdk' 
    all*.exclude group: 'com.gemstone.gemfire', module: 'gemfire' 
    all*.exclude group: 'com.tibco', module: 'tibjmsadmin'
}

dependencies { 
    implementation enforcedPlatform('group: com.citi.157514.comet, name: comet-bom, version: lso_9.5.1e_b4') 
    implementation 'org.springframework.boot:spring-boot-starter' 
    implementation 'org.springframework.boot:spring-boot-starter-actuator' 
    implementation 'org.springframework.boot:spring-boot-starter-test' 
    implementation 'commons-cli:commons-cli' 
    implementation ('com.citi.155736:OESIntF3_8:3.8_A35') { transitive = false } 
    implementation ('com.citi.157514:OES3_8:3.9_A2_b14') { transitive = false } 
    implementation 'com.citi.161969.QFIX3_8:qfix' 
    implementation ('com.citi.156783:quantum') 
    implementation 'javax.jms:javax.jms-api' 
    implementation group: 'com.tibco', name: 'tibjms' 
    implementation group: 'com.tibco', name: 'tibcrypt' 
    implementation group: 'com.tibco', name: 'tibjmsadmin', version: '8.5' 
    implementation group: 'org.springframework', name: 'spring-jms' 
    implementation group: 'org.slf4j', name: 'slf4j-api' 
    implementation 'ch.qos.logback:logback-classic' 
    implementation 'org.apache.commons:commons-dbcp2' 
    implementation files("${System.properties['java.home']}/../lib/tools.jar") 
    implementation group: 'com.solacesystems', name: 'sol-common' 
    implementation group: 'com.solacesystems', name: 'sol-jcsmp' 
    implementation group: 'com.solacesystems', name: 'sol-jws' 
    testImplementation group: 'org.powermock', name: 'powermock-api-mockito' 
    testImplementation group: 'org.powermock', name: 'powermock-module-junit4' 
    testImplementation group: 'org.powermock', name: 'powermock-module-junit4-common' 
    testImplementation 'junit:junit'
}

// ==============================================================================
// 7. APPLICATION & SCRIPTS TASKS
// UNCHANGED: Retained jar exclusions, startScript customizations, and report setups.
// ==============================================================================
jar { 
    enabled = true 
    version = "${project.version}_${project.versionBuildNumber}" 
    archiveClassifier.set('') 
    exclude('EMEA/**') 
    exclude('META-INF/**') 
    exclude('key.dat') 
    exclude('**/*.properties') 
    exclude('**/*.yml') 
    exclude('**/*.xml') 
}

startScripts { 
    unixStartScriptGenerator.template = resources.text.fromFile('src/main/scripts/customUnixStartScript.txt') 
}

task createStartScripts(type: CreateStartScripts) { 
    unixStartScriptGenerator.template = resources.text.fromFile('src/main/scripts/customUnixStartScript.txt') 
    mainClassName = 'com.citi.cet.comet.rio.collector.RioCollectorApp' 
}

spotless { enforceCheck false } 

jacoco { toolVersion = '0.8.7' } 

jacocoTestReport { 
    reports { 
        xml.enabled true 
        html.enabled true 
    } 
}

// ==============================================================================
// 8. VERIFICATION & REPORTING TASKS
// NEW / MODIFIED: Verification tasks added at the end of the script to inspect 
// TAR contents and manifest outputs automatically after 'distTar' runs.
// ==============================================================================
tasks.register('inspectDistTar') {
    description = "Inspects the generated tar file size, timestamps, and contents"
    group = "reporting"
    doLast {
        File tarFile = tasks.distTar.archiveFile.get().asFile
        if (!tarFile.exists()) {
            println "PRINT ERROR: Archive file not found at ${tarFile.absolutePath}"
            return
        }
        def sizeInMB = String.format('%.2f', tarFile.length() / (1024.0 * 1024.0))
        def timestamp = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').format(new Date())
        println "--------------------------------------------------------------------------------------------------------"
        println "PRINT BUILD SUCCESSFUL: Distribution Artifact Generated"
        println "tarFile name: ${tarFile.name}"
        println "path: ${tarFile.absolutePath}"
        println "Size: ${sizeInMB} MB (${tarFile.length()} bytes)"
        println "Timestamp: ${timestamp}"
        println "--------------------------------------------------------------------------------------------------------"
        println "--- Contents of ${tarFile.name} ---"
        int fileCount = 0
        File extractedManifest = null
        tarTree(tarFile).visit { details ->
            if (!details.directory) {
                println "[${++fileCount}] ${details.relativePath}"
                if (details.name.equalsIgnoreCase('MANIFEST.MF')) {
                    extractedManifest = details.file
                }
            }
        }
        println "--------------------------------------------------------------------------------------------------------"
        if (extractedManifest != null && extractedManifest.exists()) {
            println "MANIFEST ENTRIES (from ${extractedManifest.name}):"
            Manifest manifest = new Manifest(extractedManifest.newInputStream())
            manifest.mainAttributes.each { key, value ->
                println "    ${key}: ${value}"
            }
        } else {
            println "MANIFEST ENTRIES: No standalone MANIFEST.MF file found inside tarball."
        }
        println "--------------------------------------------------------------------------------------------------------"
    }
}

tasks.register('inspectExternalManifest') {
    description = "Reads and logs the contents of the generated external manifest.json"
    group = "reporting"
    def manifestFile = layout.buildDirectory.file("distributions/${manifestFileName}")
    inputs.file(manifestFile).optional()
    doLast {
        File f = manifestFile.get().asFile
        if (f.exists()) {
            logger.lifecycle("********************************************************************************************************")
            logger.lifecycle("--- External Manifest Inspection (${f.name}) ---")
            logger.lifecycle("Location: ${f.absolutePath}")
            logger.lifecycle(f.text)
            logger.lifecycle("********************************************************************************************************")
        } else {
            logger.warn("External manifest file not found at: ${f.absolutePath}")
        }
    }
}

// Automatically trigger inspection tasks when distTar completes
tasks.distTar.finalizedBy tasks.inspectDistTar
tasks.inspectDistTar.finalizedBy tasks.inspectExternalManifest
Enter fullscreen mode Exit fullscreen mode

Top comments (0)