/*
** Module   : build.gradle
** Abstract : gradle build script for the P2J project
**
** Copyright (c) 2017-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ------------------------------Description----------------------------------
** 001 HC  20170110 Initial version.
** 002 HC  20170124 Prevented build failure when building from unsupported bzr location while
**                  version.properties missing definitions for repo, branch and rev properties.
**                  Also indications added to inform about such a situation.
** 003 HC  20170210 Reverted h2 dependency to the custom build version 1.4.192.
**     HC  20170217 Fixed build failure when bzr not installed.
**     EVL 20170219 Fixes Windows file location command when looking for bzr installation copy.
**     HC  20170306 Removed the dependency on an external command to check availability of bzr.
** 004 HC  20170308 Split the runtime dependency configuration into conversion, client and server
**                  and added the 'ditribution' target to copy the dependencies to dist/convert,
**                  dist/client and dist/server.
** 005 HC  20170314 Added SpiVersion class.
** 006 HC  20170323 Made 'all' build target depend on 'distribution' target.
** 007 HC  20170406 Added the task createLocalRepo.
** 008 ECF 20170421 Added dependencies for jackson.
**     GES 20170503 Upgraded titan 0.4.2 and tinkerpop 2.4 to janusgraph 0.1.0 (tinkerpop 3.2.3).
** 009 HC  20170712 Fixed createLocalRepo() to explicitly invoke gradlew from the working dir.
** 010 HC  20170612 FWD Admin GWT dependencies.
** 011 HC  20170928 Reverted guava to version 19, it is the latest compatible version for
**                  org.janusgraph:janusgraph-core:0.1.0.
** 012 GES 20171019 Added Apache commons-email.
** 013 SVL 20171030 Added Jasper reports libraries.
** 014 HC  20171031 Removed dependency on the older version of Bouncy castle.
** 015 SBI 20171031 Added args4j to manage input parameters for internal tools.
** 016 ECF 20171101 Added xerces dependency to fwdCCS.
** 017 SBI 20171102 Added acme4j to use its ACME client.
** 018 CA  20180130 Added ReflectASM.
** 019 ECF 20180105 New versioning scheme for customized hibernate-core jar. Use new build
**                  (fwd-hibernate-core-4.1.8-1).
** 020 HC  20180206 Improved the artifact resolution of the createLocalRepo task to include all the needed
**                  dependencies. Previously, due to some recent changes, not all were included.
** 021 SVL 20180209 Added Apache POI.
** 022 SVL 20180310 Excluded transitive dependency of Apache POI on commons-collections4.
** 023 EVL 20180521 Adding barbecue library for barcode support.
** 024 EVL 20180522 Upgrading Jasperreports library from 6.4.3 to 6.5.1.  Adding ghost4j-1.0.1
**                  and commons-io-2.6 packages.
** 025 CA  20180814 Mark all resources with 'WARNING: this zip name is hardcoded in 
**                  WebResourceHandler', if the name is hard-coded in FWD.
** 026 ECF 20180815 Update to version 1.4.197 of fwd-h2.
** 027 CA  20181003 Added cola.js ver 3.3.9 dependency (used by FWD Analytics' flowchart).
** 028 ECF 20190326 Added junixsocket dependency. Update to latest PostgreSQL JDBC driver.
** 029 ECF 20190515 Added aspectjweaver for load-time weaving of aspects.
** 030 CA  20190717 Added Tuscany SDO (required for JavaOpenClient new compatibility APIs).
**     IAS 20190717 Added Apache Mime4j (for parsing "multipart/*").
** 031 IAS 20190926 Added httpclient dependency.
** 032 HC  20190717 Improved the build to better handle the case when no internet connectivity is
**                  present on the build system. The Gradle's dynamic nature of dependency
**                  resolution is bypassed during offline build.
** 033 HC  20191121 Added dependency javax.json-api.
** 034 HC  20200119 Added extension points to allow to externalize widget implementation.
** 035 CA  20200412 Increased the javassist, to allow support for Java 8 (required by the 
**                  incremental conversion changes, to find all implementations of a certain
**                  interface, via the Reflections API).
** 036 CA  20200701 Changed version of fwd-h2 to 1.4.197-20200530.
**     ECF 20200712 Changed version of fwd-h2 to 1.4.200-20200710. Removed Hibernate references.
**     AIL 20200728 Changed version of fwd-h2 to 1.4.200-20200727. 
** 037 HC  20200726 Initial implementation of SPREADSHEET widget and related changes.
**     CA  20200914 Added aspectjtools to fwdConvert group.
**     CA  20200915 Upgraded to Jetty 9.4.22.
**     CA  20201011 Added RoaringBitmap, a fast access bitmap for integer or long values, which can be used 
**                  instead of hash sets.
**     ECF 20201116 Changed version of fwd-h2 to 1.4.200-5. Note the naming convention change, by which the
**                  last component of the name is now the fwd-h2 revision number, rather than a sortable
**                  date.
** 038 HC  20210317 Added AspectJ Weaver dependency for IDE integration. Removed Spreadsheet backend
**                  dependency.
** 039 VVT 20210317 New target created: test to run JUnit tests in build/test-classes
**     OM  20210514 Changed version of fwd-h2 to 1.4.200-6.
**     IAS 20210608 Upgraded BouncyCastle version, added BC JSSE provider 
**     CA  20210709 Upgraded woodstox to version 6.2.6 and stax2-api to 4.2.1.
**     IAS 20210805 Added native UDFs support.
**     IAS 20210827 Use BouncyCastle jdk15to18 version
**     CA  20211112 Upgraded axiom to rev 1.2.22, as previous version was ignoring an empty SOAP header node
**                  when serializing to string.
**     RFB 20211206 Added usage of dependency-license-report, and associated configuration. Invoke with 
**                  "./gradlew cleanLicenseReport generateLicenseReport". Ref. #4037.
**     RFB 20211210 Added another plugin to generate projectReport data (text and html formatted dependencies,
**                  properties, and tasks. Cleaned up some of the license reporting. Made a single 
**                  configuration (./gradlew reports) to generate everything under ./build/reports. Ref #4037.
**     RFB 20211222 Removed explicit dependency on commons-beanutils-core as it is a dependecy of Jasper, and
**                  a newer version was being pulled in. Ref #4037.
**     IAS 20220112 Dialect-specific location of UDF SQL scripts
**     RFB 20220330 Force freemarker version to be 2.3.31 (was defaulting to 2.3.28 via gwt-validation 2.1).
**                  Ref #6219.
**     AL2 20220509 Added jsoup dependency.
**     CA  20220515 Upgraded roaringbitmap to latest version (0.9.27), some NPEs are fixed in this version.
**     IAS 20220601 Add 'words' UDFs definition to p2j.jar
**     OM  20220715 Added mariadb JDBC driver to required libraries.
**     RFB 20220809 Remove forcing of 'xml-apis' to version '1.3.04'. Ref. #6214.
**     RFB 20220810 Moved jasperreports and some of its dependencies (olap4j and itext) to the CCS dependency
**                  list, since conversion fails without it. Also removed the duplicated reflectasm 1.11.3
**                  from the Server config, since it was already included in the ClientServer config. Ref #5567.
**     RFB 20220812 Moved janusgraph-core from fwdConvert to fwdConvertServer configuration, which is brings in
**                  commons-lang3 which is required for server initialization. Ref #6671.
**     IAS 20220816 Added MariaDB udfs.sql to the p2j.jar
**     OM  20220812 Upgraded mariadb JDBC driver from 2.7.3 to 3.0.7 GA.
**     TW  20220928 Changed junixsocket dependency to official repository, and upped its version to latest.
**     TW  20221007 Upgraded junixsocket to 2.5.2.
**     TJD 20220413 Upgrade to Java 11
**     TJD 20220804 Make it compatible with both Java 8 and Java 11
**     SBI 20221121 Added gettext.js module.
**     VVT 20221216 JUnit5 dependencies updated to support both existing tests and custom test engine.
**                  See #6237.
**     SBI 20230105 Added Apache tika-core ver 1.8 without tika-parsers-standard-package due to it has
**                  transitive dependencies to newer versions of used library: jackson etc.
**     HC  20230118 Added dependency commons-collections4.
**     ECF 20230127 Upgraded mariadb JDBC driver from 3.0.7 to 3.1.2 GA.
** 040 AL2 20230224 Upgraded to the latest FWD-H2 1.12.
** 041 AL2 20230330 Upgraded to the latest FWD-H2 1.14.
** 042 AL2 20230425 Upgraded to the latest FWD-H2 1.16.
** 043 HC  20230427 Upgraded GWT to 2.10.0.
** 044 GBB 20230512 Redundant logging libs removed, slf4j impl removed.
** 045 GBB 20230517 slf4j-api and jcl-over-slf4j explicit versions.
** 046 AG  20230523 Upgraded to Roaring Bitmap to 0.9.40.
** 047 AL2 20230525 Upgraded to the latest FWD-H2 1.20.
** 048 HC  20230615 Added new task printDependencies.
** 049 VVT 20230612 junit-platform-console JAR added to the fwdClient dependencies instead of
**                  junit-platform-console-standalone. See #3827-285.
** 050 AL2 20230630 Upgraded to the latest FWD-H2 1.23.
** 051 AL2 20230706 Upgraded to the latest FWD-H2 1.24.
** 052 AL2 20231002 Upgraded to the latest FWD-H2 1.31.
** 053 AL2 20231024 Upgraded to the latest FWD-H2 1.33.
** 054 AL2 20231120 Upgraded to the latest FWD-H2 1.35.
** 055 AL2 20231120 Upgraded to the latest FWD-H2 1.38.
** 056 IAS 20230208 Added error handler support for MariaDB.
** 057 AL2 20240202 Upgraded to the latest FWD-H2 1.40.
** 058 CA  20240319 Upgraded to the latest FWD-H2 1.41.
** 059 CA  20240321 Upgraded to the latest FWD-H2 1.42.
** 060 CA  20240321 Upgraded to the latest FWD-H2 1.43.
** 061 AL2 20240402 Upgraded to the latest FWD-H2 1.44.
** 062 HC  20240405 Added dependency on tika-parsers.
** 063 CA  20240415 Upgraded to the latest FWD-H2 1.45.
** 064 HC  20240416 Removed unnecessary transitive dependencies introduced by tika-parsers by upgrading
**                  to version 2.9.x and only including the required modules.
** 065 GBB 20240419 ghost4j removed, replaced by pdfbox.
** 066 CA  20240415 Upgraded to the latest FWD-H2 1.46.
** 067 GBB 20240501 de.intarsys.opensource.jPod removed, replaced by pdfbox.
** 068 GBB 20240502 slf4j-api v2 removed from transitive dependencies of tika-core.
** 069 CA  20240502 Upgraded to the latest FWD-H2 1.47.
** 070 CA  20240502 Upgraded to the latest FWD-H2 1.48.
** 071 TJD 20221108 Java 17 compatibility changes
**     TJD 20240123 Java 17 compatibility updates
**     TJD 20240208 Java 17 dependencies updates
**     TJD 20240213 Gradle update to 7.6.4, update of Jetty to latest 9 version, dependency check plugin 
**     TJD 20240219 dependencyCheck plugin configuration
**     TJD 20240415 upgrade JS dependencies
**     TJD 20240422 upgrade com.google.gwt/org.gwtproject dependencies
**     GBB 20240422 Remove logging libs except slf4j.
**     TJD 20240423 Upgradle slf4j
**     TJD 20240430 Dependencies upgrade, switch back to jetty-all uber jar
**     TJD 20240430 Downgrade args4j to java 8 compatible version
**     TJD 20240507 Support for versioned JS dependencies in ReportWebServer
**     TJD 20240511 Switch back to jetty-all with dependencies, so they can be disabled if needed
**     CA  20240522 Exclude mime4j benchmark, as this brings jmh dependency (a benchmark tool from 
**                  openjdk), which affects javac in Java 8 (time and heap usage).
**     TJD 20240527 Restore dependency: batik-ext and explicit slf4j-api and jcl-over-slf4j
**     TJD 20240529 Removed janusgraph dependency: metrics-graphite
**     TJD 20240530 Downgraded back mariadb to FWD compatible version
** 072 SP  20240611 Fixed typo in mergePostgreSQLUDFs task.
** 073 SP  20240618 Add 'word-tables' UDFs definition to p2j.jar
** 074 CA  20240502 Upgraded to the latest FWD-H2 1.49.
** 075 AL2 20240722 Upgraded to the latest FWD-H2 1.50.
** 076 GBB 20240729 Remove always commons-logging and slf4j-simple from dependencies.
** 077 RAA 20240918 Upgraded to the latest FWD-H2 1.51.
** 078 SP  20241016 Upgraded to the latest FWD-H2 1.52.
** 079 LS  20241029 Upgraded to the latest FWD-H2 1.53.
** 080 LS  20241203 Upgraded to the latest FWD-H2-1.56.
** 081 RFB 20241118 Moved some licenseReport files to tools/licenseReport. Ref #9349.
** 082 RFB 20250121 Removed redundant dependencies which had older implementations
**                  of javax.mail. Now uses jakarta.mail-1.6.7.jar. Ref #9360
** 083 CA  20250128 Upgraded to the latest FWD-H2-1.57.
** 084 SP  20250210 Upgraded to the latest FWD-H2-1.58.
** 085 SP  20250213 Upgraded to the latest FWD-H2-1.59.
** 086 GBB 20250403 Catching java logger logs with jul-to-slf4j.
** 087 RFB 20250306 buildVersion was not correctly parsing when your checkout is using sftp. Revised
**                  to be much more robust in determining the version info.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

import com.github.jk1.license.render.*
import com.github.jk1.license.filter.*
import com.github.jk1.license.importer.*

plugins {
  id "com.dorongold.task-tree" version "2.1.1"
  id 'com.github.jk1.dependency-license-report' version '2.5'
  id "com.github.ben-manes.versions" version "0.51.0"
  id "org.owasp.dependencycheck" version "9.1.0"
  id 'project-report'
}

def buildDir = "build"
def distDir = "dist"
def libDir = "./.lib"
def reportsDir = "$buildDir/reports"

licenseReport {
    // Use the InventoryHtmlReportRender to make nice output. The tools/licenseReport/unknown-license-details.txt needs to be kept up-to-date.
    //renderers = [new CsvReportRenderer()]
    renderers = [
                  new CsvReportRenderer(), 
                  new InventoryHtmlReportRenderer('index.html', 'FWD 4.0.0 License Report', new File(projectDir,"tools/licenseReport/unknown-license-details.txt"))
                ]

    // Enable the bundle normalizer that groups disparate names, but the same license
    filters = [new LicenseBundleNormalizer()]

    // Set output directory for the report data. (Defaults to ${project.buildDir}/reports/dependency-license)
    outputDir = "$reportsDir/licenses"

    // Select projects to examine for dependencies.
    // Defaults to current project and all its subprojects
    projects = [project] + project.subprojects

    // Adjust the configurations to fetch dependencies. Use 'ALL' to dynamically resolve all configurations
    configurations = ALL
    //configurations = ['fwdAllRuntime','sheet:war']

    // List the groups ids to exclude from dependency report. Supports regular expressions.
    // For finer granularity, see: excludes.
    // These are excluded here because they are explicitly listed in the importers javascript_artifacts-front_end.xml file
    //excludeGroups = ['adamwdraper','bootstrap','cbtree','d3','font-bundle','jquery','material-components-web',
    //                 'material-design-icons','tabulator','virtualscroller','webcola','com.goldencode']

    // List the ids (in module:name format) to exclude from dependency report. Supports regular expressions.
    // By default excludes is empty.
    //excludes = ['moduleGroup:moduleName']
    //excludes = ['asm:asm']

    // Don't include artifacts of project's own group into the report
    excludeOwnGroup = true

    // Don't exclude bom dependencies.
    // If set to true, then all boms will be excluded from the report
    //excludeBoms = false

    // Set custom report renderer, implementing ReportRenderer. Yes, you can write your own to support any format necessary.
    //renderers = [new XmlReportRenderer('third-party-libs.xml', 'Back-End Libraries')]

    // Set importers to import any external dependency information, i.e. from npm.
    // Custom importer should implement DependencyDataImporter interface.
    //importers = [ new XmlReportImporter("Front End", new File(projectDir,"tools/licenseReport/javascript_artifacts-front_end.xml") ) ]

    // This is for the allowed-licenses-file in checkLicense Task
    // Accepts File, URL or String path to local or remote file
    //allowedLicensesFile = new File("$projectDir/config/allowed-licenses.json")
}

repositories {
    // https://repo1.maven.org/maven2/
    mavenCentral()
    
    maven { 
       name "maven2"
       url "https://repo1.maven.org/maven2/"
    }

    maven {
        name "jboss"
        url  "https://repository.jboss.org/nexus/content/groups/public/"
    }
    maven {
        name "goldencode"
        url  "https://proj.goldencode.com/artifacts/"
    }
    
    maven { 
       name "jitpack"
       url "https://jitpack.io/"
    }
    
    maven { 
       name "oracle"
       url "http://download.oracle.com/maven"
       allowInsecureProtocol = true
    }
    
    ivy {
        name "goldencode-javascript"
        url  "https://proj.goldencode.com/artifacts/javascript"
        patternLayout {
            artifact "[module](-[revision])(-[classifier]).[ext]"
            ivy "[module](-[revision])(-[classifier]).[ext]"
        }
        metadataSources {
           artifact()
        }
    }
    // needed for latest JasperReports
    maven { 
       name "jaspersoft"
       url "https://jaspersoft.jfrog.io/jaspersoft/jaspersoft-repo"
       allowInsecureProtocol = true
    }
}

configurations {
    antCompile
    aspectjCompile

    // all runtime dependencies needed for FWD client, FWD application server and conversion
    fwdCCS

    // all runtime dependencies needed for FWD conversion and FWD application server
    fwdConvertServer

    // all runtime dependencies needed for FWD conversion and FWD client
    fwdConvertClient

    // all runtime dependencies needed for both FWD client and FWD application server
    fwdClientServer

    // all runtime dependencies needed for FWD conversion
    fwdConvert {extendsFrom fwdCCS, fwdConvertServer, fwdConvertClient}

    gwtRuntime

    gwtCompile {extendsFrom gwtRuntime}

    // all runtime dependencies needed for FWD application server
    fwdServer {extendsFrom fwdCCS, fwdConvertServer, fwdClientServer, gwtRuntime}

    // all runtime dependencies needed for FWD client
    fwdClient {extendsFrom fwdCCS, fwdClientServer, fwdConvertClient}

    if (gradle.startParameter.isOffline()) {
        // in offline mode, the jars will be added directly from the file system
        fwdAllRuntime
        fwdAllCompile
    }
    else {
       // all runtime dependencies needed to run FWD
       // do not add dependencies to this configuration directly!
       fwdAllRuntime {extendsFrom fwdConvert, fwdServer, fwdClient}
   
       // all dependencies needed to build FWD
       // do not add dependencies to this configuration directly!
       fwdAllCompile {extendsFrom fwdAllRuntime, antCompile, aspectjCompile, gwtCompile}
    }

    // dependency exclusions
    [fwdConvert, fwdServer, fwdClient].each { c ->
                           
        // for org.apache.ws.commons.axiom
        c.exclude group: 'jaxen', module: 'jaxen'
        c.exclude group: 'org.codehaus.woodstox', module: 'wstx-asl'

        // for colt
        c.exclude group: 'concurrent', module: 'concurrent'

        c.exclude group: 'org.apache.geronimo.specs'

        // for cglib
        c.exclude group: 'asm', module: 'asm'

        // for commons-configuration
        c.exclude group: 'commons-fileupload', module: 'commons-fileupload'

        // for bcel
        c.exclude group: 'jakarta-regexp', module: 'jakarta-regexp'

        // we already have javax.servlet-api
        c.exclude group: 'javax.servlet', module: 'servlet-api'

        // for axis2
        c.exclude group: 'org.apache.woden', module: 'woden-api'
        c.exclude group: 'org.apache.woden', module: 'woden-impl-dom'
        c.exclude group: 'javax.ws.rs', module: 'jsr311-api'

        // for batik
        c.exclude group: 'xalan', module: 'xalan'

        // for javax.mail
        c.exclude group: 'javax.activation', module: 'activation'

        // for msv-core
        c.exclude group: 'isorelax', module: 'isorelax'

        // for stax2-api
        c.exclude group: 'javax.xml.stream', module: 'stax-api'

        // use com.mchange c3p0
        c.exclude group: 'c3p0', module: 'c3p0'
        
        // for JanusGraph
        c.exclude group: 'org.apache.tinkerpop', module: 'gremlin-groovysh'
        c.exclude group: 'org.apache.tinkerpop', module: 'groovy-json'
        c.exclude group: 'io.netty', module: 'netty-all'
        c.exclude group: 'io.dropwizard.metrics', module: 'metrics-graphite'
    }

    [gwtCompile, gwtRuntime].each { c ->
        // H2 prefers icu4j as the collation provider, when icu4j on the
        // classpath FWD server fails to start complaining that en_US_P2J
        // collation cannot be find
        c.exclude group: 'com.ibm.icu', module: 'icu4j'
    }

    fwdAllTest {extendsFrom fwdAllRuntime}
}

// aspectJ 1.9.7 is the last version supporting Java 8 
def aspectjVersion = '1.9.7'

if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_11)) {
// latest AspectJ version
   aspectjVersion = '1.9.21'
}

configurations.all {
    // to make sure build type is external bundling
    attributes {
       attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling, Bundling.EXTERNAL))
       attribute(TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE, 
                    objects.named(TargetJvmEnvironment, TargetJvmEnvironment.STANDARD_JVM))
    }
    
    exclude group: 'commons-logging', module: "commons-logging"
    exclude group: 'org.slf4j', module: 'slf4j-simple'
    
    // remove apis already provided by java 11+
    if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_11)) {
       exclude group: 'xml-apis', module: "xml-apis"
       exclude group: 'stax', module: 'stax-api'
    }
}

dependencies {
    fwdCCS (group: 'org.dom4j', name: 'dom4j', version: '2.1.4')
    {
        // pull parser includes javax.xml package
        exclude group: 'xpp3'
    }
   
    fwdCCS group: 'xerces', name: 'xercesImpl', version: '2.12.2'
    // Jasper reports dependencies
    fwdCCS (group: 'net.sf.jasperreports', name: 'jasperreports', version: '6.21.0') {
        exclude group: 'bouncycastle'
// to be tested
//        exclude group: 'com.fasterxml.jackson.dataformat'
    }
    // upgrade jasperreports transitive dependencies
    fwdCCS group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.17.0'
    fwdCCS group: 'org.olap4j', name: 'olap4j', version: '1.2.0'
    fwdCCS (group: 'com.lowagie', name: 'itext', version: '4.2.2') {
        exclude group: 'bouncycastle'
    }
    // check for APIs removed from JAVA 11+
    if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_11)) {
       // do not upgrade, its to replace missing API from JDK11+
       // this cannot be upgraded and must stay at version '2.3.3'
       fwdCCS group: 'jakarta.xml.ws', name: 'jakarta.xml.ws-api', version: '2.3.3'
    }
    fwdCCS group: 'org.apache.commons', name: 'commons-collections4', version: '4.4'
    fwdConvertServer group: 'antlr', name: 'antlr', version: '2.7.7'
    fwdConvertServer group: 'com.goldencode', name: 'fwd-h2', version: '1.59-trunk'
    fwdConvertServer group: 'javax.transaction', name: 'jta', version: '1.1'
    fwdConvertServer (group: 'org.janusgraph', name: 'janusgraph-lucene', version: '1.0.0')
    fwdConvertServer (group: 'org.janusgraph', name: 'janusgraph-berkeleyje', version: '1.0.0')
    
    fwdConvertClient group: 'commons-lang', name: 'commons-lang', version: '2.6'
    
    fwdConvert group: 'commons-configuration', name: 'commons-configuration', version: '1.10'
    fwdConvert group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
    fwdConvert group: 'com.fasterxml.jackson.jaxrs', name: 'jackson-jaxrs-json-provider', version: '2.16.1'
    fwdConvert group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.16.1'
    // need to add default json provider for jackson
    fwdConvert group: 'org.glassfish', name: 'javax.json', version: '1.1.4'
    fwdConvert group: 'org.aspectj', name: 'aspectjtools', version: aspectjVersion
   
    fwdClientServer group: 'org.slf4j', name: 'slf4j-api', version: '2.0.13'
    fwdClientServer group: 'org.slf4j', name: 'jcl-over-slf4j', version: '2.0.13'
    fwdClientServer group: 'org.slf4j', name: 'jul-to-slf4j', version: '2.0.13'

    // switch from jetty-uberjar to set of dependant jars to allow removing unneeded modules
    fwdClientServer (group: 'org.eclipse.jetty.aggregate', name: 'jetty-all', version: '9.4.54.v20240208') {
        exclude group: "org.eclipse.jetty.orbit", module: "javax.mail.glassfish"
        exclude group: 'org.eclipse.jetty', module: 'jetty-jaspi'
    }
    fwdClientServer group: 'org.aspectj', name: 'aspectjrt', version: aspectjVersion
    fwdClientServer group: 'commons-httpclient', name: 'commons-httpclient', version: '3.1'
    fwdClientServer group: 'commons-codec', name: 'commons-codec', version: '1.16.1'
    fwdClientServer group: 'org.apache.commons', name: 'commons-email', version: '1.6.0'
    fwdClientServer group: 'org.apache.commons', name: 'commons-text', version: '1.11.0'
    fwdClientServer group: 'org.apache.axis2', name: 'axis2-kernel', version: '1.8.2'
    // upgrade apache-mime4j-core for axis2-kernel:1.8.2
    fwdClientServer (group: 'org.apache.james', name: 'apache-mime4j-core', version: '0.8.11') {
        exclude group: 'org.apache.james', module: 'apache-mime4j-benchmark'
    }
    	
    fwdClientServer group: 'org.apache.ws.commons.axiom', name: 'axiom-api', version: '1.4.0'
    fwdClientServer group: 'org.apache.ws.commons.axiom', name: 'axiom-impl', version: '1.4.0'
    fwdClientServer group: 'org.apache.axis2', name: 'axis2-transport-http', version: '1.8.2'
    fwdClientServer group: 'org.apache.axis2', name: 'axis2-transport-local', version: '1.8.2'
    fwdClientServer group: 'org.apache.axis2', name: 'axis2-adb', version: '1.8.2'
    // args4j 2.37 is not Java 8 compatible
    fwdClientServer group: 'args4j', name: 'args4j', version: '2.33'

    fwdClientServer group: 'com.esotericsoftware', name: 'reflectasm', version: '1.11.9'
    fwdClientServer group: 'org.roaringbitmap', name: 'RoaringBitmap', version: '1.0.1'
    fwdClientServer group: 'org.conscrypt', name: 'conscrypt-openjdk-uber', version: '2.5.2'
    fwdClientServer  group: 'org.reflections', name: 'reflections', version: '0.10.2'

    // this cannot be updated as its needed for JavaOpenClient 
    fwdServer group: 'org.eclipse.emf', name: 'common', version: '2.2.3'
    fwdServer group: 'org.apache.tuscany.sdo', name: 'tuscany-sdo-impl', version: '1.1.1'
    fwdServer group: 'org.apache.tuscany.sdo', name: 'tuscany-sdo-tools', version: '1.1.1'
    fwdServer group: 'org.apache.tuscany.sdo', name: 'tuscany-sdo-lib', version: '1.1.1'
    fwdServer group: 'org.apache.tuscany.sdo', name: 'tuscany-sdo-api-r2.1', version: '1.1.1'
    fwdServer group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '3.1.2'
    
    fwdServer group: 'org.postgresql', name: 'postgresql', version: '42.7.3'
    fwdServer group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.14'
    fwdServer group: 'org.javassist', name: 'javassist', version: '3.30.2-GA'
    fwdServer group: 'org.jboss.spec.javax.transaction', name: 'jboss-transaction-api_1.1_spec', version: '1.0.1.Final'
    fwdServer group: 'org.ow2.asm', name: 'asm', version: '9.6'
    fwdServer group: 'com.mchange', name: 'c3p0', version: '0.9.5.5'
    fwdServer group: 'cglib', name: 'cglib', version: '3.3.0'
    fwdServer group: 'net.sf.ehcache', name: 'ehcache-core', version: '2.6.11'
    fwdServer group: 'org.apache.bcel', name: 'bcel', version: '6.8.1'
    fwdServer group: 'org.quartz-scheduler', name: 'quartz', version: '2.3.2'
    
    fwdServer group: 'org.bouncycastle', name: 'bcprov-jdk18on', version: '1.78.1'
    fwdServer group: 'org.bouncycastle', name: 'bcpkix-jdk18on', version: '1.78.1'
    fwdServer group: 'org.bouncycastle', name: 'bctls-jdk18on', version: '1.78.1'
    fwdServer group: 'org.bouncycastle', name: 'bcmail-jdk18on', version: '1.78.1'
    fwdServer group: 'org.bouncycastle', name: 'bcpg-jdk18on', version: '1.78.1'
    
    fwdServer group: 'net.java.dev.msv', name: 'msv-core', version: '2022.7'
    fwdServer group: 'org.codehaus.woodstox', name: 'stax2-api', version: '4.2.2'
    fwdServer (group: 'net.java.dev.stax-utils', name: 'stax-utils', version: '20070216') {
        // this is a no-JAR POM artifact which causes trouble when resolving dependencies,
        // the resolver assumes the artifact's jar file exists
        exclude group: 'com.bea.xml', module: 'jsr173-ri'
    }
    fwdServer group: 'relaxngDatatype', name: 'relaxngDatatype', version: '20020414'
    fwdServer group: 'com.fasterxml.woodstox', name: 'woodstox-core', version: '6.6.2'
    fwdServer group: 'org.aspectj', name: 'aspectjweaver', version: aspectjVersion
    
    fwdServer (group: 'net.sourceforge.barbecue', name: 'barbecue', version: '1.5-beta1') {
        exclude group: 'bouncycastle'
    }
    fwdServer group: 'commons-io', name: 'commons-io', version: '2.15.1'
    fwdServer (group: 'org.apache.james', name: 'apache-mime4j', version: '0.8.9') {
        exclude group: 'org.apache.james', module: 'apache-mime4j-benchmark'
    }
    fwdServer (group: 'org.apache.poi', name: 'poi', version: '5.2.5') {
         exclude group: 'org.apache.commons'
    }
    fwdServer group: 'com.kohlschutter.junixsocket', name: 'junixsocket-common', version: '2.8.3'
    fwdServer group: 'com.kohlschutter.junixsocket', name: 'junixsocket-native-common', version: '2.8.3'

    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-svggen', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-gvt', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-transcoder', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-codec', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-extension', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-gui-util', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'batik-swing', version: '1.17'
    fwdClient group: 'org.apache.xmlgraphics', name: 'xmlgraphics-commons', version: '2.9'
    fwdClient group: 'com.twelvemonkeys.common', name: 'common-image', version: '3.10.1'
    fwdClient group: 'com.twelvemonkeys.common', name: 'common-io', version: '3.10.1'
    fwdClient group: 'com.twelvemonkeys.common', name: 'common-lang', version: '3.10.1'
    fwdClient group: 'com.twelvemonkeys.imageio', name: 'fwd-imageio-bmp', version: '3.10.1' // custom imageio-bmp having memory leak patched
    fwdClient group: 'com.twelvemonkeys.imageio', name: 'imageio-metadata', version: '3.10.1'
    fwdClient group: 'org.dojotoolkit', name: 'dojo', version: '1.17.3', classifier: 'distribution', ext: 'zip' // WARNING: this zip name is hardcoded in DojoToolkitHandler and ReportWebServer
    fwdClient (group: 'org.webjars.npm', name: 'd3', version: '4.13.0') { // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
        // disable transitive dependencies
        exclude group: 'org.webjars.npm'
    }
    fwdClient group: 'adamwdraper', name: 'adamwdraper-Numeral-js', version: '7de892f', ext: 'zip'
    fwdClient group: 'org.webjars', name: 'bootstrap', version: '3.4.1' // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
    fwdClient group: 'cbtree', name: 'cbtree', version: 'v0.9.4', classifier: '0', ext: 'zip'  // WARNING: this zip name is hardcoded in  ReportWebServer
    fwdClient group: 'font-bundle', name: 'font-bundle', version: 'v1', ext: 'zip' // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
    fwdClient group: 'jquery', name: 'jquery-loading-overlay', version: '1.5.3', ext: 'zip' // WARNING: this zip name is hardcoded in  ReportWebServer
    fwdClient group: 'org.webjars', name: 'jquery', version: '3.7.1' // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
    fwdClient group: 'org.webjars', name: 'jquery-ui', version: '1.13.2' // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
    fwdClient group: 'material-components-web', name: 'material-components-web', version: '0.37.0', ext: 'zip' // WARNING: this zip name is hardcoded in WebResourceHandler
    fwdClient group: 'material-design-icons', name: 'material-design-icons', version: '96', ext: 'zip' // WARNING: this zip name is hardcoded in WebResourceHandler
    fwdClient group: 'tabulator', name: 'tabulator-master', version: '2.12.0', ext: 'zip' // WARNING: this zip name is hardcoded in WebResourceHandler and ReportWebServer
    fwdClient group: 'virtualscroller', name: 'virtualscroller', version: '1', ext: 'zip' // WARNING: this zip name is hardcoded in  ReportWebServer
    fwdClient group: 'webcola', name: 'webcola', version: '3.3.9', ext: 'zip'
    fwdClient group: 'javax.json', name: 'javax.json-api', version: '1.1.4'
    fwdClient group: 'org.jsoup', name: 'jsoup', version: '1.17.2'
    fwdClient group: 'gettext', name: 'gettext.js', version: '1.2.0', ext: 'zip' // WARNING: this zip name is hardcoded in WebResourceHandler
    fwdClient (group: 'org.apache.tika', name: 'tika-core', version: '2.9.2') {
        exclude group: 'org.slf4j', module: 'slf4j-api'
    }
    fwdClient group: 'org.apache.tika', name: 'tika-parser-text-module', version: '2.9.2'
    fwdClient group: 'org.apache.tika', name: 'tika-parser-html-module', version: '2.9.2'
    // com.google.gwt was renamed to org.gwtproject
    modules {
        module('com.google.gwt:gwt-user') {
            replacedBy 'org.gwtproject:gwt-user', 'org.gwtproject'
        }
        module('com.google.gwt:gwt-dev') {
            replacedBy 'org.gwtproject:gwt-dev', 'org.gwtproject'
        }
    }
    gwtRuntime (group: 'org.gwtproject', name: 'gwt-user', version: '2.11.0')
    gwtRuntime group: 'org.freemarker', name: 'freemarker', version: '2.3.32'
    gwtRuntime (group: 'com.gwtplatform', name: 'gwtp-mvp-client', version: '1.6') {
        // gwt-dev is not needed on the runtime
        exclude group: 'com.google.gwt', module: 'gwt-dev'
    }
    gwtRuntime (group: 'com.gwtplatform', name: 'gwtp-dispatch-rest', version: '1.6') {
        // the following dependencies are not needed on the runtime
        exclude group: 'com.google.gwt', module: 'gwt-dev'
        exclude group: 'com.gwtplatform', module: 'gwtp-clients-common'
        exclude group: 'com.gwtplatform', module: 'gwtp-dispatch-common-shared'
        exclude group: 'com.gwtplatform', module: 'gwtp-dispatch-rest-shared'
        exclude group: 'org.eclipse.jdt', module: 'ecj'
    }
    gwtRuntime group: "org.gwtbootstrap3", name: "gwtbootstrap3", version: "1.0.1"
    gwtRuntime group: "org.gwtbootstrap3", name: "gwtbootstrap3-extras", version: "1.0.2"
    gwtRuntime group: 'com.google.guava', name: 'guava-gwt', version: '33.1.0-jre'
    gwtRuntime group: 'org.apache.pdfbox', name: 'pdfbox', version: '2.0.31'
    gwtRuntime group: 'org.apache.pdfbox', name: 'fontbox', version: '2.0.31'
    gwtCompile (group: 'org.gwtproject', name: 'gwt-dev', version: '2.11.0') {
        exclude group: 'org.eclipse.jdt', module: 'ecj'
    }
    gwtCompile group: 'org.gwtproject', name: 'gwt-codeserver', version: '2.11.0'
    gwtCompile group: 'com.google.j2objc', name: 'j2objc-annotations', version: '2.8'
    
    if (gradle.startParameter.isOffline()) {
        fwdAllCompile  fileTree(dir: "${libDir}/fwdAllCompile")
        fwdAllRuntime  fileTree(dir: "${libDir}/fwdAllRuntime")
        antCompile     fileTree(dir: "${libDir}/antCompile")
        aspectjCompile fileTree(dir: "${libDir}/aspectjCompile")
    }
    else {
       // javascript Nashorn has been removed from JDK15, so we need it back
       if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_15)) {
          antCompile "org.openjdk.nashorn:nashorn-core:15.4"
       }
       antCompile "org.apache.ant:ant-antlr:1.10.14"
       aspectjCompile group: 'org.aspectj', name: 'aspectjtools', version: aspectjVersion
       aspectjCompile group: 'org.aspectj', name: 'aspectjrt', version: aspectjVersion
       aspectjCompile group: 'org.aspectj', name: 'aspectjweaver', version: aspectjVersion
    }

    // Adding JUnit5 jar both to client and server, so it will be also deployed to converted projects
    fwdClientServer group: 'org.junit.platform', name: 'junit-platform-engine', version: '1.10.2'
    fwdClientServer group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.10.2'
    fwdClientServer group: 'org.junit.platform', name: 'junit-platform-suite-engine', version: '1.10.2'
    fwdClientServer group: 'org.apiguardian', name: 'apiguardian-api', version: '1.1.2'
    
    fwdClient group: 'org.junit.platform', name: 'junit-platform-console', version: '1.10.2'
}

// inject ant-optional dependencies to ant, this is needed for the antlr ant target
def antClassLoader = org.apache.tools.ant.Project.class.classLoader
configurations.antCompile.each { File f ->
    antClassLoader.addURL(f.toURI().toURL())
}

ant.importBuild('build.xml')

ant.path(id: 'compile.classpath', path: configurations.fwdAllCompile.asPath)
ant.path(id: 'runtime.classpath', path: configurations.fwdAllRuntime.asPath)
ant.path(id: 'tests.classpath', path: configurations.fwdAllTest.asPath)
ant.path(id: 'aspectjCompile.classpath', path: configurations.aspectjCompile.asPath)
ant.properties['go-gradle'] = 'false'

task cleanDistribution {
    doLast {
        delete {
            delete "${distDir}/convert", "${distDir}/server", "${distDir}/client"
        }
    }
}

task cleanReports {
    doLast {
        delete {
            println "Clearing $reportsDir directory..."
            delete "$reportsDir"
        }
    }
}

task reports {
    dependsOn 'cleanReports'
    dependsOn 'projectReport'
    dependsOn 'generateLicenseReport'

    tasks.findByName('projectReport').mustRunAfter 'cleanReports'
    tasks.findByName('generateLicenseReport').mustRunAfter 'projectReport'
    doLast {
        println "Generating report information for licenses and projects in $reportsDir directory..."
    }
}

task distribution(dependsOn: cleanDistribution) {
    doLast {
        copy {
            into "${distDir}/convert"
            from configurations.fwdConvert
        }
        copy {
            into "${distDir}/client"
            from configurations.fwdClient
        }
        copy {
            into "${distDir}/server"
            from configurations.fwdServer
        }
    }
}

def version = "undefined"

/**
 * The task builds the product version string, the version information is read from the file
 * version.properties.
 */
task buildVersion() {
    doLast {
        Properties props = new Properties()
        props.load(new FileInputStream("$projectDir/version.properties"))
        def versionFormat = props.getProperty("format")?.trim()
        if (!versionFormat) {
            versionFormat = "<major>.<minor>.<release>_<repo>_<branch>_<rev>"
        }

        def major = props.getProperty("major")?.trim()
        def minor = props.getProperty("minor")?.trim()
        def release = props.getProperty("release")?.trim()
        def repo = props.getProperty("repo")?.trim()
        def branch = props.getProperty("branch")?.trim()
        def rev = props.getProperty("rev")?.trim()

        if (!repo || !branch) {
            println "Fetching repository name and branch from bzr info..."
            // bzr info may yield many formats:
            //     Internal on devsrv01 (all contain a URI + "/code/p2j_repo/<repo>"):
            //        /home/<user>/secure/code/p2j_repo/<repo>/trunk or
            //        /home/<user>/secure/code/p2j_repo/<repo>/active/<branch> or
            //        S:/code/p2j_repo/<repo>/trunk or
            //        S:/code/p2j_repo/<repo>/active/<branch>
            //        bzr+ssh://<user>@localhost:2224/opt/secure/code/p2j_repo/<repo>/trunk
            //        bzr+ssh://<user>@localhost:2224/opt/secure/code/p2j_repo/<repo>/active/<branch>
            //     External on xfer.goldencode.com (all formats lead to "/opt/fwd", which is repo=p2j):
            //        sftp://<user>@xfer.goldencode.com/opt/fwd/trunk/ or
            //        sftp://<user>@xfer.goldencode.com/opt/fwd/<branch>
            try
            {
                new ByteArrayOutputStream().withStream { os ->
                    def res = exec {
                        executable = 'bzr'
                        args = ['info']
                        standardOutput = os
                        ignoreExitValue = true
                        workingDir = projectDir
                    }
                    if (res.exitValue == 0) {
                        def outstr = os.toString().trim().replaceAll("\\\\", "/").replaceAll(/\/+$/, "")

                        // Extract repo name (internal or external)
                        if (outstr.contains("/code/p2j_repo/")) {
                            def matcher = outstr =~ /\/code\/p2j_repo\/([^\/]+)/  // Get repo name after "/code/p2j_repo/"
                            if (matcher.find()) {
                                repo = matcher.group(1)
                            }
                        } else if (outstr.contains("/opt/fwd")) {
                            repo = "p2j"  // Hardcoded override for "/opt/fwd"
                        }

                        // Extract branch name using the detected repo
                        if (repo && outstr.contains("/code/p2j_repo/${repo}/")) {
                            def branchMatcher = outstr =~ /\/code\/p2j_repo\/${repo}\/(?:active\/([^\/]+)|trunk)\/*$/
                            if (branchMatcher.find()) {
                                branch = branchMatcher.group(1) ?: "trunk"  // Extract branch if "active", else it's "trunk"
                            }
                        } else if (outstr.contains("/opt/fwd/")) {
                            def branchMatcher = outstr =~ /\/opt\/fwd\/(.+)\/*$/
                            if (branchMatcher.find()) {
                                branch = branchMatcher.group(1)  // Whatever follows "/opt/fwd/" is the branch
                            }
                        }
                    } else {
                        logger.warn("WARN: Could not find repository name and branch in 'bzr info' output!")
                    }
                }
            }
            catch (Exception ex)
            {
                println(ex);
            }
        }

        if (!repo) {
            logger.warn("WARN: Unable to resolve repository name. Make sure you build " +
                    "from a supported bzr repository location or the property repo is " +
                    "defined in version.properties.")
        }

        if (!branch) {
            logger.warn("WARN: Unable to resolve branch name. Make sure you build from " +
                    "a supported bzr repository location or the property branch is " +
                    "defined in version.properties.")
        }

        if (!rev) {
            println "Fetching revision number from bzr revno..."
            try
            {
                new ByteArrayOutputStream().withStream { os ->
                    def res = exec {
                        executable = 'bzr'
                        args = ['revno']
                        standardOutput = os
                        ignoreExitValue = true
                        workingDir = projectDir
                    }
                    if (res.exitValue == 0) {
                        rev = os.toString().trim()
                    }
                }
            }
            catch (Exception ex)
            {
                println(ex);
            }
        }

        if (!rev) {
            logger.warn("WARN: Unable to resolve revision number. Make sure you build from " +
                    "a supported bzr repository location or the property rev is defined in " +
                    "version.properties.")
        }

        if (!rev) rev = "undefined"
        if (!branch) branch = "undefined"
        if (!repo) repo = "undefined"
        if (!release) release = "undefined"
        if (!minor) minor = "undefined"
        if (!major) major = "undefined"

        version = versionFormat.replace("<major>", major).replace("<minor>", minor).replace("<release>", release).replace("<repo>", repo).replace("<branch>", branch).replace("<rev>", rev)

        println "Product version: ${version}"

        // remove manifests so that the current built version is picked up
        file("${buildDir}/manifest").deleteDir()

        // add version to Version.java and SpiVersion.java
        copy {
            from 'src/com/goldencode/p2j/Version.java'
            into "${buildDir}/gen/src/java/com/goldencode/p2j"
            expand(versionString: version)
        }
        copy {
            from 'src/com/goldencode/p2j/SpiVersion.java'
            into "${buildDir}/gen/src/java/com/goldencode/p2j"
            expand(versionString: version)
        }
        // add version to the getFWDVersion SQL UDF
        copy {
            from 'udf/postgresql/getFWDVersion.sql'
            into "${buildDir}/udf/postgresql"
            expand(versionString: version)
        }
        // add 'words' udfs
        copy {
            from 'udf/postgresql'
            into "${buildDir}/udf/postgresql"
            include('words-udfs-*.sql', 'word-tables.sql')
        }
        // add MariaDB udfs (it is NOT the final version!)
        copy {
            from 'udf/mariadb/getFWDVersion.sql'
            into "${buildDir}/udf/mariadb"
            expand(versionString: version)
        }
      }
}

task makeManifests(dependsOn: 'buildVersion') {
    doLast {
        def classpath = configurations.fwdAllRuntime.collect {it.getName() }.join(' ')
        copy {
            from 'manifest'
            into "${buildDir}/manifest"
            include '*.mf.template'
            rename { file -> file.replace(".template", "") }
            expand(versionString: version, fwdManifestClasspath: classpath)
        }
    }
}

task mergePostgreSQLUDFs(dependsOn: 'makeManifests') {
    inputs.files('udf/postgresql/udfs.sql', 
                 'udf/postgresql/guarded.sql', 
                 'udf/postgresql/error_handler.sql', 
                 "${buildDir}/udf/postgresql/getFWDVersion.sql")
    outputs.file( "${buildDir}/udf/postgresql/udfs.sql" )
    doLast {
        outputs.files.singleFile.withOutputStream { out ->
            for ( file in inputs.files ) file.withInputStream { out << it << '\n' }
        }
    }
}

task mergeMariaDBUDFs(dependsOn: 'makeManifests') {
    inputs.files('udf/mariadb/udfs.sql', 
                 'udf/mariadb/guarded.sql', 
                 'udf/mariadb/error_handler.sql', 
                 "${buildDir}/udf/mariadb/getFWDVersion.sql")
    outputs.file( "${buildDir}/udf/mariadb/udfs.sql" )
    doLast {
        outputs.files.singleFile.withOutputStream { out ->
            for ( file in inputs.files ) file.withInputStream { out << it << '\n' }
        }
    }
}

/**
 * Fetches all dependencies from the artifact repositories and the dependency configurations. The fetched files are stored
 * in $libDir directory and can be used to build the project without internet connectivity. When running this task, do not
 * use the --offline Gradle parameter. On the other hand, use --offline when the dependencies have been fetched and no
 * internet connectivity is available.
 */
task fetchDependencies() {
    doLast {
        delete(libDir)
        ['fwdAllCompile', 'fwdAllRuntime', 'aspectjCompile', 'antCompile', 'fwdServer', 'fwdClient'].each { cfg ->
            copy {
                from configurations.getByName(cfg).files
                into "${libDir}/${cfg}"
            }
        }
    }
}

/**
 * Gradle task to print and create a JSON representation of the dependencies for a given configuration.
 *
 * It takes a command line property 'config' as the configuration name.
 * If no 'config' property is provided, it defaults to 'fwdAllRuntime'.
 *
 * The task first checks if the configuration exists. If it does not, it prints a warning message.
 * If the configuration does exist, it prints all the dependencies and generates a JSON array of
 * dependencies that have .jar files. Each JSON object in the array includes the group ID, name,
 * and version of the dependency.
 *
 * The generated JSON is then printed to the console.
 *
 * Usage:
 * Run the task without parameters to use the default configuration:
 *     ./gradlew printDependencies
 *
 * Run the task with a custom configuration:
 *     ./gradlew printDependencies -Pconfig=customConfigName
 */
task printDependencies() {
    doLast {
        String configurationName = findProperty('config') ?: 'fwdAllRuntime'

        // Check if the configuration exists
        if (!configurations.findByName(configurationName)) {
            println "Configuration $configurationName does not exist. Please provide a valid configuration name."
        } else {
            // Now, print the dependencies of the specified configuration
            def json = '['

            configurations.getByName(configurationName).resolvedConfiguration.resolvedArtifacts.each { artifact ->
                if(artifact.extension == 'jar') {
                    def id = artifact.moduleVersion.id
                    json += '{"group":"' + id.group + '", "name":"' + id.name + '", "version":"' + id.version + '"},'
                }
            }

            if (json != null && json.length() > 0 && json.charAt(json.length() - 1) == ',') {
                json = json.substring(0, json.length() - 1);
            }

            json += ']'

            println(json)
        }
    }
}

/**
 * Fetches the Gradle distribution for offline build. To use the distribution on a fresh system without internet connectivity
 * set the property distributionUrl in gradle/wrapper/gradle-wrapper.properties to ../../lib/gradle-3.0-bin.zip.
 */
task fetchGradle() {
    doLast {
        def f = new File('lib/gradle-7.6.4-bin.zip')
        if (!f.exists()) {
            new URL('https://services.gradle.org/distributions/gradle-7.6.4-bin.zip').withInputStream{ i -> f.withOutputStream{ it << i }}
        }
    }
}

tasks['ant-prepare'].dependsOn('mergePostgreSQLUDFs','mergeMariaDBUDFs')
tasks['ant-clean'].dependsOn cleanDistribution

apply from: 'admin.gradle'
tasks['ant-admin_build'].dependsOn buildAdmin

task test(type: JavaExec) {
  classpath = configurations.fwdAllTest + files('build/test-classes', 'build/classes')
  main = 'org.junit.platform.console.ConsoleLauncher'
  args '--scan-classpath=build/test-classes'
}
tasks['test'].dependsOn('ant-tests-compile')

dependencyCheck {
    // possible formats are: HTML, XML, CSV, JSON, JUNIT, SARIF, JENKINS, GITLAB, ALL
    formats = [ 'CSV' , 'HTML' ]
    scanConfigurations=[ 'fwdAllRuntime' ]
    analyzers.nodeAudit.yarnEnabled = false
}

configure(fetchDependencies) {   
    group = 'FWD'
    description = 'Fetches all dependencies from the artifact repositories and the dependency configurations'
}

configure(printDependencies) {   
    group = 'FWD'
    description = 'Gradle task to print and create a JSON representation of the dependencies for a given configuration.'
}
